- 162 Find Peak Element
题意:返回数组中的其中一个peak
思路:二分
- 165 Compare Version Numbers
题意:序列号比较
思路:split后处理
class Solution {
public:
int compareVersion(string version1, string version2) {
vector<string> vs1 = split_help(version1);
vector<string> vs2 = split_help(version2);
int index_1 = 0,size_1 = vs1.size();
int index_2 = 0,size_2 = vs2.size();
if(size_1 == 0) return -1;
if(size_2 == 0) return 1;
while(index_1 < size_1 && index_2 < size_2){
if(vs1[index_1].size() == 0 && vs2[index_2].size() > 0){
return -1;
}else if(vs1[index_1].size() > 0 && vs2[index_2].size() == 0){
return 1;
}else if(vs1[index_1].size() > 0 && vs2[index_2].size() > 0){
int tmp1 = 0,tmp2 = 0,i = 0,j = 0;
while(i < vs1[index_1].size()){
tmp1 = tmp1 * 10 + vs1[index_1][i] - '0';
i ++;
}
while(j < vs2[index_2].size()){
tmp2 = tmp2 * 10 + vs2[index_2][j] - '0';
j ++;
}
if(tmp1 > tmp2) return 1;
if(tmp1 < tmp2) return -1;
}
index_1 += 1;
index_2 += 1;
}
while(index_1 < size_1){
for(int i = 0;i < vs1[index_1].size();++ i) if(vs1[index_1][i] > '0') return 1;
index_1 ++;
}
while(index_2 < size_2){
for(int i = 0;i < vs2[index_2].size();++ i) if(vs2[index_2][i] > '0') return -1;
index_2 ++;
}
// for(string s : vs2) cout<<s<<' ';
return 0;
}
vector<string> split_help(string s){
vector<string> ret;
int index = 0,begin = 0;
while(index < s.size()){
while(s[index] != '.' && index < s.size()) index ++;
// cout<<begin<<' '<<index<<endl;
// cout<<s.substr(begin,index - begin)<<endl;
ret.push_back(s.substr(begin,index - begin));
index += 1;
begin = index;
}
return ret;
}
};
- 166 Fraction to Recurring Decimal
题意:除法模拟
思路:map
class Solution
{
public:
string fractionToDecimal(long long numerator, long long denominator)
{
string result;
stringstream ss;
if ((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0))
{
ss << '-';
}
numerator = abs(numerator);
denominator = abs(denominator);
long long intPart = numerator / denominator;
long long r = numerator % denominator;
ss << intPart;
ss >> result;
if (!r)
{
return result;
}
unordered_map<long long, size_t> table;
result += '.';
while (r)
{
if (table.find(r) != table.end())
{
size_t index = table.at(r);
result.insert(index, 1, '(');
result += ')';
break;
}
else
{
table.emplace(r, result.size());
char toAppend = r * 10 / denominator + '0';
r = r * 10 % denominator;
result += toAppend;
}
}
return result;
}
};
- 167 Two Sum II - Input array is sorted
题意:有序数组中找和为target的两个数
思路:two point
- 168 Excel Sheet Column Title
题意:数字的变换
这个傻逼题目真的是。。。
class Solution {
public:
string convertToTitle(int n) {
string ret = "";
while(n){
int curr = n % 26;
// curr = curr == 0 ? 26 : curr;
if(curr == 0){
curr = 26;
n -= 26;
}
ret += ('A' + curr - 1);
n /= 26;
}
reverse(ret.begin(), ret.end());
return ret;
}
};
- 169 Majority Element
题意:出现概率大于0.5的数字