In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in the order of increasing from left to right, and each column is sorted in the order of increasing from top to bottom. Please complete a function, input such a two-dimensional array and an integer, to determine whether the array contains the integer.
dichotomy
public class Solution { //The idea this time is to do a binary search on each line. public boolean Find(int target, int [][] array) { int rows=array.length; int columns=array[0].length-1; //It's classic to be familiar with binary lookup code. for(int i=0;i<rows;i++){ int low=0,high=columns; //Here is less than or equal to!! If the condition of self-judgment is wrongly written, it can also be carried out. while(low<=high){ int mid=(low+high)/2; if(target<array[i][mid]) //That's what you remember, because the target is on the left, so high is moving to the left, so it's minus one. high=mid-1; else if(target>array[i][mid]) low=mid+1; else return true; } } return false; } }
Using the law of increasing from top to bottom and from left to right of two-dimensional arrays
Start at the lower left or upper right corner
public class Solution { public boolean Find(int [][] array,int target) { 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; } }
Attention points
Two-dimensional array
- Two-dimensional arrays in java are made up of many rows!! Two-dimensional arrays. length is rows.
dichotomy
- In dichotomy, +1, -1 are all for mid.
- You find your target (the target value you want to find), on the left of mid, let mid-1
- You find your target (the target value you want to find), on the right side of mid, let mid+1
- The condition is while (low <= high)