Find a two-dimensional array of 0001
Title Description
(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.
Topics address
- https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e
Report problem-solving
Violence Act
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
One by one through the array, if found return true
/**
* 微信公众号"小猿刷题"
*/
public class Solution {
public boolean Find(int target, int [][] array) {
for(int i = 0; i < array.length; i ++){
for(int j = 0; j < array[i].length; j++){
if(target == array[i][j]){
return true;
}
}
}
return false;
}
}
Local binary search
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
Progressive traversal, binary search within each row.
/**
* 微信公众号"小猿刷题"
*/
public class Solution {
public boolean Find(int target, int [][] array) {
for(int i = 0; i< array.length; i++){
int low = 0;
int high = array[i].length - 1;
while (low <= high){
int mid = (low + high) / 2;
if(target > array[i][mid]){
low = mid + 1;
} else if(target < array[i][mid]){
high = mid - 1;
} else {
return true;
}
}
}
return false;
}
}
Overall binary search
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
A two-dimensional array from top to bottom, from left to right in increasing regularity, then select the upper or lower left corner of the element array[row][col]
and target are compared.
- When
target
less than the elementarray[row][col]
when ittarget
must be an element inarray
the left side of the row, namelycol--
; - When
target
elements greater thanarray[row][col]
the time, thentarget
certainly in the elementarray
below where the columns, namelyrow++
;
/**
* 微信公众号"小猿刷题"
*/
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]) {
row ++;
} else if(target < array[row][col]) {
col --;
} else {
return true;
}
}
return false;
}
}