代码随想录算法训练营 DAY1 | 二分查找

代码随想录算法训练营 DAY1 | 二分查找_第1张图片

 

二分查找模板

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

    }
};

1.统一格式,双闭区间,左右可等

2.防溢出,int mid =left + (right-left)/2

3.二分查找模块化,变成功能型函数

例题:leetcode704

实战 leetcode 27 移除元素

class Solution {
public:
    int removeElement(vector& nums, int val) {
        sort(nums.begin(),nums.end());
        int length =nums.size();
        while(search(nums,val)!=-1){
            length-=1;
        }
        return length;

    }

    int search(vector& nums, int target) {
        int left =0;
        int right =nums.size() -1;
        while(left<=right){
            int mid =left + (right-left)/2;
            if(nums[mid]==target){
                nums.erase(nums.begin()+mid);
                return mid;
            }else if(nums[mid]>target){
                right = mid -1;
            }else{
                left = mid+1;
            }
        }
        return -1;

    }
};

解析:把二分查找模块化,当成辅助查找的函数,以便提高代码效率

你可能感兴趣的:(算法日记,算法,leetcode,数据结构)