leetcode: Search a 2D Matrix

159 篇文章 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;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值