算法系列——Search a 2D Matrix
阿新 • • 發佈:2019-02-13
題目描述
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.
解題思路
題目要求在二維陣列中搜索。這個二維陣列有特徵,每一行從左往右遞增,每列從上往下遞增。搜尋時我們應該充分利用這個特徵。我們可以從陣列右上角元素開始搜尋,凡是比它小的應該在它左側(j–),比它值大的在它下方(i++)。通過不斷比較給定元素下個右上角元素的值,我們可以不斷縮小搜尋範圍。最終找到 指定元素。平均時間複雜度為O(m+n)
程式實現
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null||matrix.length==0)
return false;
int m=matrix.length;
int n=matrix[0].length;
int 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)
i++;
else
j--;
}
return false;
}
}