码迷,mamicode.com
首页 > 其他好文 > 详细

240. Search a 2D Matrix II

时间:2015-11-30 00:44:04      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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,

Consider the following matrix:

[
  [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]
]

Given target = 5, return true.

Given target = 20, return false.

链接: http://leetcode.com/problems/search-a-2d-matrix-ii/

题解: 

在行和列排序好的二维数组中查找目标数字。这里我们用了一个很巧妙的方法,从矩阵的右上角开始找,相当于把这个元素当作mid,目标比mid大,则row + 1,小则col + 1,相等则返回mid。也是类似二分查找的思想。

Time Complexity - O(m + n), Space Complexity - O(1)

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0)
            return false;
        int row = 0, col = matrix[0].length - 1;
        
        while (row < matrix.length && col >= 0) {
            int curElem = matrix[row][col];
            if(curElem == target)
                return true;
            else if(curElem < target)
                row++;
            else
                col--;
        }
        
        return false;
    }
}

 

测试:

https://leetcode.com/discuss/47506/ac-clean-java-solution

https://leetcode.com/discuss/48852/my-concise-o-m-n-java-solution

https://leetcode.com/discuss/66657/java-short-code-o-m-n

240. Search a 2D Matrix II

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5005947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!