Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91382715
welcome to my blog
Interview questions 4: a two-dimensional array to find
Thinking
- Compare the top right corner to find the numbers and size of digital relationship
- If the number is greater than the upper-right corner of the digital're looking for, where the top-right corner of the digital ignored
- If the number is less than the number you want to find the top right corner of the row numbers where the upper right corner are ignored
the complexity
- time complexity:
- Space complexity:
public class Solution {
public boolean Find(int target, int [][] array) {
// 健壮性判断
if(array.length <=0 ){
return false;
}
// 正式判断; 判断右上角的元素和要查找的元素的大小关系, 结果有三种可能: 1,忽略列, 2,忽略行, 3,返回true 把这三种情况想清楚了, 这题就简单了
int row = 0;
int col = array[0].length - 1;
while(row <= array.length - 1 && col >= 0){
if(array[row][col] == target)
return true;
else if(array[row][col] > target)
col--;
else
row++;
}
return false;
}
}