二分查找简单题

Leetcode 35. Search Insert Position
最普通的Binary Search,若target存在,则返回所在下标;若target不存在,则返回target待插入的位置,本质上就是实现lower_bound函数

无论mid = left + ( right - left ) / 2,还是mid = left + ( right - left + 1 ) / 2,最后当target不存在时,一定要返回left,不能返回right

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;

        while( left <= right )
        {
            int mid = left + ( right - left ) / 2;

            if( target == nums[mid] )
                return mid;
            else if( target > nums[mid] )
                left = mid + 1;
            else
                right = mid - 1;
        }

        return left;
    }
};

Leetcode 240. Search a 2D Matrix II
经典题,从矩阵右上角开始查找,要么向左,要么向下

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();

        if( m == 0 )
            return false;

        int n = matrix[0].size();
        int i = 0, j = n - 1;

        while( i < m && j >= 0 )
        {
            if( target == matrix[i][j] )
                return true;
            else if( target > matrix[i][j] )
                i++;
            else
                j--;
        }

        return false;
    }
};

你可能感兴趣的:(Binary,Search)