23.1.12Leetcode x 的平方根/加一/最后一个单词的长度/搜索插入位置/移除元素 c++

移除元素

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);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值