首页 > 其他 > 详细

leetcode: Search a 2D Matrix

时间:2016-06-12 04:02:19      阅读:327      评论: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 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.

?

原问题链接:https://leetcode.com/problems/search-a-2d-matrix/

?

问题分析

Young tableaus

  这个问题有好几种思路可以解决。一种方法在之前的文章里也有讨论过。这种方法就是基于young tableaus来做的。就是在开始的时候从矩阵的右上角开始。每次用目标元素和这个位置的元素进行比较,如果目标元素比这个值小,则列值减一,如果目标元素比这个元素大,则行值加一。这样从斜角一直移动到一个点。如果最终没有找到目标元素则返回false。这种方法的时间复杂度为O(m + n),其中m, n分别为矩阵的行数和列数。

  按照这种思路,代码的实现如下:

?

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

?

binary search

  除了上述的办法,如果我们仔细看问题的描述,还会发现一个方法。就是它每一行是递增的。而且每后面一行的第一个元素比前一行最后的元素要大。这说明如果我们把整个矩阵按照每行这么排列的展开,它就构成了一个排序的数组。而在一个排序的数组里找一个给定的元素,很显然,上二分搜索就搞定了。?

?

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length, start = 0, end = m * n -1;

        while(start <= end){
            int mid = (start + end) / 2;
            int tempRow = (mid / n);
            int tempCol = (mid % n);

            if(matrix[tempRow][tempCol] == target) return true;
            else if(matrix[tempRow][tempCol] < target) start = mid + 1;
            else end = mid - 1;
        }
        return false;
    }
}

?

?

leetcode: Search a 2D Matrix

原文:http://shmilyaw-hotmail-com.iteye.com/blog/2303206

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!