劍指01.二維陣列中的查詢
阿新 • • 發佈:2020-08-01
題目描述
在一個二維陣列中(每個一維陣列的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。案例
輸入:7,返回true ; 輸入5, 返回false
方法1:暴力法
public class Solution { public boolean Find(int target, int [][] array) { //判斷陣列是否為空 if(array.length == 0 || array[0].length == 0) return false時間複雜度:O(n^2),因為最壞情況下,陣列中的元素都需要遍歷一次。; 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; } }
空間複雜度:O(1)
方法2:從右上找
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) returnfalse; //判斷陣列是否為空 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)