1. Lookup in a 2D array
Topic description
In a two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.
Ideas:
利用二维数组由上到下,由左到右递增的规律,
那么选取右上角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 row=0; int col=array[0].length-1; while(row<=array.length-1&&col>=0){ if(target==array[row][col]) return true; else if(target>array[row][col]) row++; else col--; } return false; } }
Notice:
For a 2D array:
int[][] arr = { {2,3,4}, {4,5,6}, {7,8,9} };
int rows = i.length;//行数
int columns = i[0].length;//列数
[[]] Such an array represents 1 for the number of rows and 0 for the number of columns.