美莉人生

快乐着,享受着...

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

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;
    }
    
};


阅读更多
个人分类: Leet Code --Array
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭