关闭

【Leet Code】74. Search a 2D Matrix---Medium

125人阅读 评论(0) 收藏 举报
分类:

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

思路:

解决该题目的方法就是对一维数组的二分查找进行变形操作,先对中间行对一维数组的二分查找,如果找到就返回true。

如果没找到,如果target<matrix[mid][0],则令down=mid-1;否则,up=mid+1.

代码实现:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.size() < 1 || matrix[0].size() < 1) return false;
        int up = 0, down = matrix.size()-1;
        int mid = 0;
        while(up <= down)
        {
            mid = (up + down)/2;
            if(searchArray(matrix[mid], target)) return true;
            
            if(target < matrix[mid][0]) down = mid -1;
            else up = mid + 1;
        }
        return false;
    }
private:
    bool searchArray(vector<int>& nums, int target){
        int left = 0, right = nums.size() -1;
        int mid = 0;
        while(left <= right)
        {
            mid = (left + right)/2;
            if(target == nums[mid])
                return true;
            if(target > nums[mid])
                left = mid + 1;
            else right = mid - 1;
        }
        return false;
    }
    
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7136次
    • 积分:373
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条