Middle-题目32: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 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 https://blog.csdn.net/cmershen/article/details/51546423
个人分类: Leetcode
上一篇Middle-题目31:11. Container With Most Water
下一篇Middle-题目33:300. Longest Increasing Subsequence
想对作者说点什么? 我来说一句

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

关闭
关闭