就是沿着右上角或者左下角进行判断
package question4_find_in_arrays;
/**
* @Classname Solution1
* @Description TODO
* @Date 2020/3/7 2:23
* @Created by mmz
*/
public class Solution1 {
public static boolean findsolution(int[] arr,int row,int col,int number){
boolean found = false;
if(arr!= null && row>0&& col>0){
int rows = 0;
int cols = col-1;
while(rows<row && cols>0){
if(number ==arr[rows*col+cols]){
found = true;
break;
}else if(number >arr[rows*col+cols]){
rows++;
}else{
cols--;
}
}
}
return found;
}
public static void main(String[] args) {
int[] arr = new int[]{1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
System.out.println(Solution1.findsolution(arr, 4, 4, 119));
}
}
20200331——二刷
package question4_find_in_arrays;
/**
* @Classname Solution2
* @Description TODO
* @Date 2020/3/31 13:45
* @Created by mmz
*/
public class Solution2 {
static boolean findNumber(int[][] arr,int number){
int xend = arr.length-1;
int yend = arr[0].length-1;
int i = 0;
int j = yend;
while(0<=i&& i<=xend && 0<=j &&j<=yend){
int temp = arr[i][j];
if(arr[i][j] == number){
return true;
}
if(number>arr[i][j]){
i++;
}else if(arr[i][j]>number){
j--;
}
}
return false;
}
public static void main(String[] args) {
int[][] arr = new int[][]{{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
int number = 1;
System.out.println(findNumber(arr, number));
}
}
这回使用的是二维数组进行排序,while循环内部体来判断。
重要的点是i,j
i其实确定的是第几行而不是第几列了。
所以逻辑要反过来去写。
二刷2020/04/11
package question4_二维数组中的查找;
/**
* @Classname Main
* @Description TODO
* @Date 2020/4/11 14:58
* @Created by mmz
*/
public class Main {
public static boolean Core(int[][] arr,int tartget){
int xlength = arr[0].length-1;
int ylength = arr.length-1;
int xstart = xlength;
int ystart = 0;
while(ystart<ylength && xstart>=0){
if(tartget == arr[ystart][xstart]){
return true;
}else if(tartget > arr[ystart][xstart]){
ystart++;
}else{
xstart--;
}
}
return false;
}
public static void main(String[] args) {
int[][] arr = new int[][]{{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
int number = 20;
System.out.println(Main.Core(arr, number));
}
}
一遍成,主要判断边界,逻辑不是很复杂。
三刷20200718
package question4_二维数组中的查找;
/**
* @Classname Mmz
* @Description TODO
* @Date 2020/7/18 14:08
* @Created by mmz
*/
public class Mmz {
public static boolean Core(int[][] nums,int target){
if(nums == null){
return false;
}
int i = 0;
int j = nums[0].length-1;
while(j>=0 && i<nums.length){
if(nums[i][j] == target){
return true;
}else if(nums[i][j] > target){
j--;
}else{
i++;
}
}
return false;
}
public static void main(String[] args) {
int[][] arr = new int[][]{{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
int number = 40;
System.out.println(Core(arr, number));
}
}
每一遍编程都有不同的想法。