代码随想录算法训练营第一天|数组part1

704.二分查找

题目链接

class Solution {
public:
    int search(vector& nums, int target) {
        int l = 0;
        int r = nums.size()-1;
        while(l <= r){
            int t = (l + r)/2;
            if(nums[t] == target){
                return t;
            }
            else if(nums[t] < target){
                l = t+1;
            }
            else{
                r = t-1;
            }
        }
        return -1;
    }
};

27.移除元素

题目链接

class Solution {
public:
    int removeElement(vector& nums, int val) {
        int res = nums.size();
        for(int i = 0; i < res; i++){
            if(nums[i] == val){
                nums[i] = nums[--res];
                i--;
            }
        }
        return res;
    }
};

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,数据结构)