移除元素
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int fast = 0,slow = 0;
while(fast<n){
if(nums[fast] != val){
nums[slow]=nums[fast];
slow++;
}
fast++;
}
return slow;
}
};
搜索插入位置
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int l=0,r=n-1;
while(l<=r){
int mid=(l+r)/2;
if(nums[mid]<target){
l=mid+1;
}else r=mid-1;
}
return l;
}
};
最后一个单词的长度
class Solution {
public:
int lengthOfLastWord(string s) {
int index = s.size()-1;
while(s[index] == ' '){
index--;
}
int wordlength = 0;
while(index>=0 && s[index] != ' '){
wordlength++;
index--;
}
return wordlength;
}
};
加一
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
for(int i=n-1;i>=0;i--){
if(digits[i]==9){
digits[i]=0;
}else{
digits[i]+=1;
return digits;
}
}
vector<int> ans(n+1);
ans[0] = 1;
return ans;
}
};
x 的平方根
牛顿迭代法是一种可以用来快速求解函数零点的方法。
牛顿迭代法的本质是借助泰勒级数,从初始值开始快速向零点逼近。
class Solution {
public:
int mySqrt(int x) {
if(x == 0){
return 0;
}
double c=x,x0=x;
while(true){
double xi = 0.5*(x0+c/x0);
if(fabs(x0-xi)<1e-7){
break;
}
x0=xi;
}
return int(x0);
}
};