输入:7,返回true ; 输入5, 返回false
public class Solution { public boolean Find(int target, int [][] array) { //判断数组是否为空 if(array.length == 0 || 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 boolean Find(int target, int [][] array) { //每次取右上角的数字,与target进行对比 //如果该数字大于target,则剔除这个数字所在的列 //如果该数字小于target,则剔除这个数字所在的行 int rows = array.length; //一共有多少行 int columns = array[0].length; //一共有多少列 if (rows == 0 || columns == 0) return false; //判断数组是否为空 int row = 0; int col = columns - 1; while (row < rows && col >= 0 ){ if (array[row][col] > target){ col--; }else if (array[row][col] < target){ row++; }else return true; } return false; } }
时间复杂度:O(m+n) ,其中m为行数,n为列数,最坏情况下,需要遍历m+n次。
空间复杂度:O(1)
原文:https://www.cnblogs.com/HuangYJ/p/13416471.html