搜尋二維陣列
阿新 • • 發佈:2018-12-21
編寫一個高效的演算法來判斷 m x n 矩陣中,是否存在一個目標值。
該矩陣具有如下特性:
- 每行中的整數從左到右按升序排列。
- 每行的第一個整數大於前一行的最後一個整數。
示例 1:
輸入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
輸出: true
示例 2:
輸入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
輸出: false
題目分析
根據此矩陣的特性,每一行的第一個元素比前一行的最後一個元素大,並且每一行中元素從小到大排序,所以相當於一個從小到大排列的數字序列存在於二維陣列中,要查詢目標值的話,首先可以用目標值和第一行最後一個元素比較,如果相等,返回true;如果目標值小於此數,那麼就在這一行尋找;如果目標值大於此數,則令行數增加,繼續尋找。
程式碼實現
public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0) return false; int rowIndex = 0; int colIndex = matrix[0].length - 1; while (rowIndex < matrix.length && colIndex >= 0) { if (target == matrix[rowIndex][colIndex]) return
true; else if (target > matrix[rowIndex][colIndex]) rowIndex++; else colIndex--; } return false; }
主函式
public static void main(String[] args) { S7 s = new S7(); boolean res1 = s.searchMatrix(new int[][]{{1,3,5,7},{10,11,16,20},{23,30,34,50}}, 3); boolean
res2 = s.searchMatrix(new int[][]{{1,3,5,7},{10,11,16,20},{23,30,34,50}}, 13); System.out.println(res1); System.out.println(res2); }
執行結果
true false