LeetCode -- Search a 2D Matrix & Search a 2D Matrix II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode -- Search a 2D Matrix & Search a 2D Matrix II相关的知识,希望对你有一定的参考价值。
Question: Search a 2D Matrix
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
.
Analysis:
写出一个算法,能够找出一个m * n矩阵中是否含一个数。这个m*n的矩阵有如下性质:
1. 每行的整数从左到右是有序的;
2. 每行的第一个整数要比上一行的最后一个整数大。
思路:
不论是单行有序或整体有序,都可以使用这样的策略解决问题:
从矩阵的右上角开始寻找,如果target比他大,则往下找;如果target比他小,则往左找,如果矩阵中确实存在这个数,则一定能找到,若找到最后也没有找到,则返回false。
这道题目还可以用二分法解决。用两次二分法,先找到行,再找到列。(但是对于单行有序的题目来说则不适合解决)
Answer:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int row = matrix.length; int col = matrix[0].length; int i = 0; int j = matrix[0].length-1; while(i < matrix.length && j >= 0) { if(matrix[i][j] == target) return true; else if(matrix[i][j] < target) i++; else if(matrix[i][j] > target) j--; } return false; } }
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
.
Analsyis:
这个题目与上面不同的是,矩阵的性质是:
1. 每行从走到有是有序的;
2. 每列从上到下是有序的;
但满足这两个性质并不能保证这个矩阵整体是有序的,因此用二分法一定不能解决问题,但是我们可以使用上面从右上角开始,更新i,j的值来寻找矩阵中是否存在这个元素的方法。
Answer:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int row = matrix.length; int col = matrix[0].length; int i = 0; int j = matrix[0].length-1; while(i < matrix.length && j >= 0) { if(matrix[i][j] == target) return true; else if(matrix[i][j] < target) i++; else if(matrix[i][j] > target) j--; } return false; } }
以上是关于LeetCode -- Search a 2D Matrix & Search a 2D Matrix II的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode]240. Search a 2D Matrix II