LeetCode 74. Search a 2D Matrix

原创 2018年04月16日 15:39:02

没想到方法一利用展开二维数组,二分查找,各个行的元素按照mod的变换来计算

将二维数组按行展开的话,就是一个排序的一维数组,因此通过一维数组的二分查找很容易得到答案。

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        int rows=matrix.size();
        int cols=matrix[0].size();
        int left=0,right=(rows*cols-1);
        int mid,r,c,val;
        while(left<=right){
            mid=left+((right-left)>>1);
            r=mid/cols;
            c=mid%cols;
            if(matrix[r][c]==target)
                return true;
            if(matrix[r][c]<target)
                left=mid+1;
            else
                right=mid-1;
        }
        return false;
    }
};

第二种方法

先通过二分查找元素所在的行,再在所在行通过二分查找元素。

LeetCode74——Search a 2D Matrix

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

LeetCode 74:Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo...
  • geekmanong
  • geekmanong
  • 2016-01-20 21:49:29
  • 1454

74 Search a 2D Matrix

题目链接:https://leetcode.com/problems/search-a-2d-matrix/题目:Write an efficient algorithm that searches ...
  • ChilseaSai
  • ChilseaSai
  • 2015-10-22 20:36:35
  • 777

LeetCode(074) Search a 2D Matrix (Java)

题目如下: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the...
  • feliciafay
  • feliciafay
  • 2015-04-13 12:37:58
  • 872

leetcode 240: Search a 2D Matrix II

leetcode 240: Search a 2D Matrix II python java c++
  • xudli
  • xudli
  • 2015-07-23 06:07:35
  • 12003

【LEETCODE】74-Search a 2D Matrix [Python]

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the foll...
  • aliceyangxi1987
  • aliceyangxi1987
  • 2016-01-07 16:04:59
  • 501

leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo...
  • xygy8860
  • xygy8860
  • 2015-07-19 16:35:54
  • 566

【leetcode】74. Search a 2D Matrix【java】

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo...
  • cslbupt
  • cslbupt
  • 2016-12-20 16:56:50
  • 409

[leetcode] 74. Search a 2D Matrix 解题报告

题目链接:https://leetcode.com/problems/search-a-2d-matrix/ Write an efficient algorithm that search...
  • qq508618087
  • qq508618087
  • 2016-01-02 08:48:44
  • 355

Search a 2D Matrix -- LeetCode

原题链接: http://oj.leetcode.com/problems/search-a-2d-matrix/  这道题是二分查找Search Insert Position的题目,因为矩阵...
  • linhuanmars
  • linhuanmars
  • 2014-04-21 02:29:21
  • 12496
收藏助手
不良信息举报
您举报文章:LeetCode 74. Search a 2D Matrix
举报原因:
原因补充:

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