目录
一、x的平方根
二分法
最高位先对半取加一,然后进行二分查找,找到比所求数小的便赋值给ans,直到出现大于且low大于high的时候便输出ans。
class Solution {
public:
int mySqrt(int x) {
int low = 0;
int high = x / 2 + 1;
int ans = -1;
while(low <= high){
int mid = low + (high - low) / 2;
if ((long long)mid * mid <= x) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
};
二、寻找比目标字母大的最小字母
二分法
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
int n = letters.size();
int low = 0;
int high = n - 1;
int ans = 0;
while(low <= high){
int mid = low + (high - low)/2;
if(letters[mid] <= target){
ans = (mid + 1) % n;
low = mid + 1;
}else{
high = mid - 1;
}
}
return letters[ans];
}
};
三、反转字符串
双指针
指头和指尾,不断靠近就可以搞定了
class Solution {
public:
void reverseString(vector<char>& s) {
int n = s.size();
for(int i = 0, j = n - 1;i <= j; i++, j--){
int tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
};
递归
class Solution {
public:
void reverseString(vector<char>& s, int i = 0) {
if(i >= (s.size() - i - 1)) return;
reverseString(s, i + 1);
int tmp = s[i];
s[i] = s[s.size() - i - 1];
s[s.size() - i - 1] = tmp;
}
};
四、反转字符串中的单词 III
双指针
j指针往后移动,找到空格,就移动i指针进行换位。然后在最后一个字母处没有空格了,需要再移位一次。
class Solution {
public:
string reverseWords(string s) {
int n = s.size();
int i, j;
for(i = 0, j = 0; j < n; j++){
if(s[j] == ' '){
for(int m = j - 1; i <= m; i++, m--){
int tmp = s[i];
s[i] = s[m];
s[m] = tmp;
}
i = j + 1;
}
}
for(j = j - 1; i <= j; i++, j--){
int tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
return s;
}
};