二维数组中查找数字
题目链接
https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github
题目描述
给定一个二维数组,其每一行从左到右递增排序,从上到下也是递增排序。给定一个数,判断这个数是否在该二维数组中。
[
[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.
package com.huang.datastructure;
public class ErArrayDemo {
public static void main(String[] args) {
int[][] arr = new int[5][5];
arr[0][0] = 1;
arr[0][1] = 4;
arr[0][2] = 7;
arr[0][3] = 11;
arr[0][4] = 15;
arr[1][0] = 2;
arr[1][1] = 5;
arr[1][2] = 8;
arr[1][3] = 12;
arr[1][4] = 19;
arr[2][0] = 3;
arr[2][1] = 6;
arr[2][2] = 9;
arr[2][3] = 16;
arr[2][4] = 22;
arr[3][0] = 10;
arr[3][1] = 13;
arr[3][2] = 14;
arr[3][3] = 17;
arr[3][4] = 14;
arr[4][0] = 18;
arr[4][1] = 21;
arr[4][2] = 23;
arr[4][3] = 26;
arr[4][4] = 30;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
boolean b = find2(100, arr);
System.out.println(b);
}
public static boolean find(int target,int[][] arr) {
if(arr == null || arr.length == 0 || arr[0].length ==0) {
return false;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if(arr[i][j] == target) {
return true;
}
}
}
return false;
}
public static boolean find2(int target,int[][] arr) {
if(arr == null || arr.length == 0 || arr[0].length ==0) {
return false;
}
int rows = arr.length,cols = arr[0].length;
int r = 0,c = cols - 1;
while (r <= rows - 1 && c >= 0){
if(target == arr[r][c]){
return true;
}else if(target > arr[r][c]){
r++;
}else {
c--;
}
}
return false;
}
}