Middle-题目32:240. Search a 2D Matrix II

原创 2016年05月31日 15:52:51

题目原文:
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
题目大意:
在一个满足下列性质的矩阵中寻找一个数:
每一行从左到右,每一列从上到下的数组是递增顺序的。
题目分析:
初始化i=0,j=n-1,即从矩阵的右上角开始找。若当前数比target小,则i++(因为只有下面才有更大的数,这样直接排除掉第i行),若当前数比target大,则j–(因为只有左面才有更小的数,这样直接排除掉第j列),如果找到边缘还没找到,则返回false。
源码:(language:java)

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length==0)
            return false;
        int rows=matrix.length,cols=matrix[0].length;
        int i=0,j=cols-1;
        while(j>=0 && i<=rows-1) {
            if(matrix[i][j] == target)
                return true;
            else if(matrix[i][j] < target)
                i++;
            else
                j--;
        }
        return false;
    }
}

成绩:
13ms,beats 56.57%,众数13ms,37.38%
Cmershen的碎碎念:
这道题很经典,传说是MSRA的面试题,因为每次都排除一行(列),而(i,j)点始终位于新矩阵的右上角,故可以看做是一个分治算法,算法很巧妙值得借鉴。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

LeetCode240. Search a 2D Matrix II题解

1. 题目描述Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has...
  • lby0910
  • lby0910
  • 2017年03月03日 19:30
  • 166

[Leetcode]74(240). Search a 2D Matrix I,II

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

LeetCode 240. Search a 2D Matrix II 解题报告

LeetCode 240. Search a 2D Matrix II 解题报告题目描述Write an efficient algorithm that searches for a value i...

leetcode 240. Search a 2D Matrix II

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

【LEETCODE】240-Search a 2D Matrix II

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

Leetcode 240. Search a 2D Matrix II[medium]

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

LeetCode No.240 Search a 2D Matrix II

LeetCode No.240 Search a 2D Matrix II

LeetCode240. Search a 2D Matrix II二分查找+分治法

题意:一个矩阵,每一行都是升序,每一列都是升序。快速判断该矩阵是否有某个值。我起初是这样做的,但是超时了。class Solution { public: bool searchMatrix(...

[leetcode]240. Search a 2D Matrix II

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

Leetcode——240. Search a 2D Matrix II

descriptionWrite an efficient algorithm that searches for a value in an m x n matrix. This matrix ha...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目32:240. Search a 2D Matrix II
举报原因:
原因补充:

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