题解 | #寻找牛群中的特定编号牛#

寻找牛群中的特定编号牛

https://www.nowcoder.com/practice/e0c6f3fba6dd40b99e8bcc0241631f9d

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix int整型vector<vector<>> 
     * @param target int整型 
     * @return bool布尔型
     */
    bool searchMatrix(vector<vector<int> >& matrix, int target) {
        // write code here
        int m = matrix.size();
        int n = matrix[0].size();
        int left = 0 ;
        int right = m-1;
        int mid;
        while(left <= right){
            mid = (left + right) / 2;
            if(matrix[mid][0] >= target && matrix[mid][n-1] <= target){
                break;
            }
            if(matrix[mid][0] < target){
                right = mid - 1;
            }
            if(matrix[mid][n-1] > target){
                left = left + 1;
            }
        }
        vector<int> &target_vec = matrix[mid];
        left = 0;
        right = n - 1;
        while(left <= right){
            mid = (left + right) / 2;
            if(target == target_vec[mid]){
                return true;
            }
            if(target < target_vec[mid]){
                left = mid + 1;
            }
            if(target > target_vec[mid]){
                right = mid - 1;
            }
        }
        return false;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务