链接:
https://www.nowcoder.com/questionTerminal/abc3fe2ce8e146608e868a70efebf62e
来源:牛客网
注:
链接:
https://www.nowcoder.com/questionTerminal/abc3fe2ce8e146608e868a70efebf62e
来源:牛客网
来源:牛客网
一种思路是:
利用二维数组由上到下,由左到右递增的规律,
那么选取右上角或者左下角的元素a[row][col]与target进行比较,
当target小于元素a[row][col]时,那么target必定在元素a所在行的左边,
即col--;
当target大于元素a[row][col]时,那么target必定在元素a所在列的下边,
即row++;
public class Solution {
public boolean Find(int target, int [][] array) {
int i=0;
int j=array[0].length-1;
while(j>=0&&i<=array.length-1){
if(array[i][j]==target){
return true;
}
else if(array[i][j]>target){
j--;
}
else{
i++;
}
}
return false;
}
注:
num.length是num数组的长度
num[i].length是num数组中包含数组的长度。
你可以不要把它看成二维数组,直接看成 数组的数组 !
那便可理解,num.length是二维数组中的主数组的长度,num[i].length是其中分数组的长度
[1 , 2 , 3
4 , 5 , 7]
例如上面,主数组大小是num.length = 2.
分数组大小(i == 0)是num[i].length = 3 当i=0表示第一排数组的大小,这个就为3;
一种是:
把每一行看成有序递增的数组,
利用二分查找,
通过遍历每一行得到答案,
时间复杂度是nlogn
来源:牛客网
public class Solution {
publicboolean Find(int[][] array,int target) {
for(inti=0;i<array.length;i++){
intlow=0;
inthigh=array[i].length-1;
while(low<=high){
intmid=(low+high)/2;
if(target>array[i][mid])
low=mid+1;
elseif(target<array[i][mid])
high=mid-1;
else
returntrue;
}
}
returnfalse;
}
}