Two-dimensional array of find - Offer to prove safety

Title Description

In a two-dimensional array (the same as the length of each one-dimensional array),
Each row is incremented from left to right in the order sort,
Each column from top to bottom in accordance with incremental sort order.
A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.
 

Problem-solving ideas

Required time complexity O (M + N), the spatial complexity is O (1). Where M is the number of rows, N being the number of columns.

A number of two-dimensional array, is less than a certain number in which it left , is greater than a certain number of its lower side thereof .

Therefore, start looking from the top right, you can narrow down the range depending on the size relationship between the target and the current element, the element of the current search interval for all elements of the lower left corner.

From cyc2018

    

     
   Boolean the Find public (target int, int [] [] Array) {
     // empty judgment is first
IF (Array == null || 0 || be array.length == Array [0] .length == 0 ) { return to false ; }
     // get the number of rows and columns
int rows = be array.length, cols = Array [0 ] .length;
     // index variable is defined
int R & lt = 0, = C-cols. 1 ;
     // from the top right to bottom left find angle turn
the while (R & lt <= && rows. 1-C> = 0 ) {
       // find the target digital
IF (target == Array [R & lt] [C]) { return to true ; }
       // current number is less than the target digital
IF (target < Array [R & lt] [C]) { C - ; } the else {// number is greater than the current target digital R & lt ++ ; } }
     // find complete until a two-dimensional array, We did not find the target number.
return to false ; }

 

Cattle off-line programming problem

cyc2018 problem-solving ideas

Guess you like

Origin www.cnblogs.com/yuyu97513/p/11465420.html