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

原创 2015年11月17日 17:03:57

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] Search a 2D Matrix

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

LeetCode 74. Search a 2D Matrix

1. 题目描述 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has...

[74] Search a 2D Matrix

对有序二维数组进行二分查找
  • camlot_
  • camlot_
  • 2015年09月01日 14:51
  • 229

LeetCode74——Search a 2D Matrix

LeetCode74——Search a 2D Matrix 二维数组查找问题,二重循环暴力搜索肯定是超时的,好在二维数组有一定的规律: 1.每一行从左到右是非递减的 2.每一列从上到下是非递减...

529. Minesweeper\74. Search a 2D Matrix

Minesweeper 题目描述 代码实现529. Minesweeper题目描述Let’s play the minesweeper game (Wikipedia, online game)!Yo...

【leetcode】【74】Search a 2D Matrix

一、问题描述 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has ...

LeetCode刷题(C++)——Search a 2D Matrix(Medium)

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

LeetCode 74. Search a 2D Matrix (C++ JavaScript)

LeetCode 74 Search a 2D Matrix C++ && JavaScript 搜索 && 二分查找

leetcode || 74、Search a 2D Matrix

problem: Write an efficient algorithm that searches for a value in an m x n matrix. This matri...

Leetcode 74 Search a 2D Matrix 有序二维数组二叉查找

Leetcode 74 Search a 2D Matrix 在一个二维数组中查找是否存在某元素,该二维数组具有以下特性: - 每一行中的元素都是递增的 - 每一行行中最小的元素比上一行最大的元...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:【Leet Code】74. Search a 2D Matrix---Medium
举报原因:
原因补充:

(最多只允许输入30个字)