LeetCode每日一题之整数反转
在一个二维数组array中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]
给定target=7,返回true
给定target=3,返回false
思路
1、这道题核心就在于设置两个索引,实现对行和列中元素的定位
2、一方面可以暴力解法,遍历数组中的全部元素
3、另一方面可以取巧一些,通过逐级比较大小,来确定行索引的移动,还是列索引的移动,得到最终值
解法:
方法一:遍历全部元素
public class Solution {
public static void main(String[] args) {
int[][] arr = {{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15}};
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
System.out.println(searchArray1(arr, x));
}
public static boolean searchArray1(int[][] array, int target) {
if (array == null || array.length == 0 || array[0] == null || array[0].length == 0) {
return false;
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if (array[i][j] == target) {
return true;
}
}
}
return false;
}
}
方法二:逐级优化比较
public class Solution {
public static void main(String[] args) {
int[][] arr = {
{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15}};
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
System.out.println(searchArray(arr, x));
}
public static boolean searchArray(int[][] array, int target) {
if(array == null || array.length == 0 || array[0] == null || array[0].length == 0){
return false;
}
int row = array.length;
//确定有几行
int column = array[0].length;
//确定数组有几列
int down = 0;
//设置一个列索引完成定位坐标的上下移动
int right = column - 1;
//同上,完成左右移动
while(down<row&&right>=0){
//限制索引,使其不发生越界 down<row 即down不能超过总行数; right<column-1 ,即这个索引是从右往左指向,从大到小指向。逐渐缩小范围
if(array[down][right] == target){
return true;
}
if(array[down][right] > target){
right--;
}else{
down++;
}
}
return false;
}
}