题目描述:
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路
第一种思路
暴力破解,直接循环遍历,然后进行查询看有没有这个整数
第二种思路
因为题目显示的是说二维数组是从上到下,从左到右依次递增的
这种规律给了我们很好的思路
我们从左下角开始,如果比左下角的大右移,如果比左上角的小,左移,这样最终会找到结果的
代码实现
第一种思路
public class Solution { public static void main(String[] args) { int[][] array = new int[][]{ {1,2,3}, {2,3,4}, {3,4,5} }; int target = 2; System.out.println(Find(target,array)); } public static boolean Find(int target, int [][] array) { if(array.length==0) return false; for(int i = 0;i < array.length; i++) { for(int j=0; j < array[i].length; j++){ if(array[i][j] == target) return true; } } return false; } }
|
第二种思路
public class Solution { public static void main(String[] args) { int[][] array = new int[][]{ {1,2,3}, {2,3,4}, {3,4,5} }; int target = 7; System.out.println(Find(target,array)); } public static boolean Find(int target, int [][] array) { if(array.length==0 || array[0].length==0) return false; int row = array.length-1; int col = 0; while (row >= 0 && col<=array.length-1) { if(target > array[row][col]) col++; else if(target < array[row][col] ) row--; else return true; } return false; }
|