Title Description
In a two-dimensional array, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, enter a two-dimensional array and an integer to determine if the array contains the integer.
Idea One:
The two-dimensional array as a binary tree, the lower left corner of the tree is the midpoint, smaller than the target to go up, greater than target to the right. is actually a binary search tree.
Code implementation:
1 Public classSolution {2 Public BooleanFind (intTargetint[] Array) {3 if(Array = =NULL|| Array.Length = = 0| | Array[0] = =NULL|| Array[0].length = = 0){4 return false;5 }6 intLen = array.length-1;7 intLen2 = array[0].length-1;8 if(Array[0][0] >target)9 return false;Ten if(Array[len][len2] <target) One return false; A inti =Len; - intj = 0; - while(I >= 0 && J <=len2) { the if(Array[i][j] = =target) { - return true; -}Else if(Array[i][j] <target) { -J + +; +}Else{ -i--; + } A } at return false; - - } -}
Idea two:
Using binary search, the matrix is regarded as the upper triangle and the lower triangle, and the two points are searched separately.
Code implementation:
Public Static BooleanFind (int[] Array,inttarget) { if(Array = =NULL|| Array.Length = = 0 | | Array[0] = =NULL|| Array[0].length = = 0){ return false; } intLow,high,mid; for(intj = 0; J < Array.Length; J + +) { low=J; High= Array.length-1; Mid= (low + high)/2; while(Low <=High ) {System.out.println (array[mid][j]); if(Array[mid][j] = =target) { return true; } if(Array[mid][j] >target) { High= Mid-1; }Else{ Low= Mid + 1; } Mid= (low + high)/2; } } for(inti = 0; i < array.length-1; i++) { low= i + 1; High= Array[i].length-1; Mid= (low + high)/2; while(Low <=High ) {System.out.println (Array[i][mid]); if(Array[i][mid] = =target) { return true; } if(Array[i][mid] >target) { High= Mid-1; }Else{ Low= Mid + 1; } Mid= (low + high)/2; } } return false; }
Sequential lookups are not recommended.
Finding in a two-dimensional array