Title Descriptionin 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. Example: 1 2 8 92 4 94 7 10 13
6 8 11 15
returns True if the number 9 is found in this array. Returns False if the number of sub 5 is found. Analysis: Because each row of a two-bit array is ordered in ascending order from left to right, each column is sorted in ascending order from top to bottom.
the usual idea might be to compare the diagonal, but if the number you are looking for may appear in two regions and overlap in the current position ,that would be a problem. so an easier way is to pick the number in the upper right corner of the array (the current number), the number to find (the number of targets), if the current number is greater than the target number, because the column is incremented from top to bottom, then the current number of the column can be excluded, so that the current number of lines to reduce one, become a new More. Example:Find the number 7 from the upper-right corner, the current number is 9, 9 is greater than 7, then 9 of the column cannot have a number of 7, this column excludes. The row label is reduced to a new two-bit array, the new current number is selected 8, 8 is greater than 7, and the same is omitted from this column.
Current number 2, less than 7, when the list is added one, the first row is removed.
Current number 4, less than 7, when the list is added one, the first row is removed.
The current number 7, which is equal to 7, returns True.
The following lists the C + + and Java implementations separately
C++:
1#include <bits/stdc++.h>2 3 using namespacestd;4 5 intMain ()6 {7 inta[4][4] = {8{1,2,8,9},9{2,4,9, A},Ten{4,7,Ten, -}, One{6,8, One, the}, A } ; - intN; -CIN >> N;//the element to find the intI=0 ; - intj=3 ; - while((i<=3) && (j>=0)){ - if(a[i][j]>N) { +j-- ; -}Else if(a[i][j]<N) { +i++ ; A}Else if(a[i][j]==N) { atcout <<"Yes"<<Endl; - Break ; - } - } - return 0 ; -}
Java:
1 ImportJava.util.Scanner;2 3 Public classFind {4 Public Static voidMain (string[] args) {5 intA[][] = {6{1, 2, 8, 9},7{2, 4, 9, 12},8{4, 7, 10, 13},9{6, 8, 11, 15},Ten }; One intN; AScanner cin =NewScanner (system.in); -n =cin.nextint (); - intI=0 ; the intJ=a.length-1; - while((i<=3) && (j>=0)){ - if(a[i][j]>N) { -j-- ; +}Else if(a[i][j]<N) { -i++ ; +}Else if(a[i][j]==N) { ASYSTEM.OUT.PRINTLN ("Yes"); at Break ; - } - } - } -}
The search in the two-dimensional array of the sword finger offer_4_