Find prove safety Offer two-dimensional array of digital topics

topic:


(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


Ideas:

Because each row is incremented each column is incremented, so that each row of the leftmost row is the smallest, largest rightmost one line, or select the top right corner lowermost,
when the target is less than the element a [row] [col], the then the target must be left in a row of elements,
i.e. col--;
when the target is greater than the element a [row] [col] when, the target must be located in the lower element of a column,
i.e. row ++;

 

Code:

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;
}

Guess you like

Origin www.cnblogs.com/hmy-BigData/p/11885275.html