Leetcode演算法Java全解答--74. 搜尋二維矩陣
阿新 • • 發佈:2018-12-26
Leetcode演算法Java全解答–74. 搜尋二維矩陣
文章目錄
題目
編寫一個高效的演算法來判斷 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
想法
- 先編歷第一列的資料,找到那個比target大的資料,那麼target在這一項的前一行(遍歷1/10/23)
在關鍵行使用二分查詢
2.陳獨秀方法(better),把二維陣列轉換成一個一維陣列,直接上二分查詢
座標轉換:matrix[i][j] <=> matrix[a] 其中a=i*n+j, i=a/n, j=a%n;
結果
超過98%的測試案例
時間複雜度/空間複雜度:n/1
總結
程式碼
我的答案
public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0 || matrix[0][0] > target) { return false; } int muchTargetIndex = -1; for (int i = 0; i < matrix.length; i++) { if (matrix[i][0] == target) { return true; } else if (matrix[i][0] > target) { muchTargetIndex = i - 1; break; } else { muchTargetIndex++; } } int left = 0; int right = matrix[muchTargetIndex].length - 1; int center = 0; while (left <= right) { center = left + (right - left) / 2; if (matrix[muchTargetIndex][center] == target) { return true; } else if (matrix[muchTargetIndex][center] > target) { right = center - 1; } else { left = center + 1; } } return false; }
大佬們的答案
public boolean better(int[][] matrix, int target) { if(matrix.length == 0) { return false; } int m = matrix.length; int n = matrix[0].length; int low = 0, high = m * n; while(low < high){ int mid = (low + high) / 2; if(matrix[mid / n][mid % n] == target){ return true; }else if(matrix[mid / n][mid % n] < target){ low = mid + 1; }else{ high = mid; } } return false; }
測試用例
@Test
public void test074() {
// 建立測試案例
int[][] arr1 = new int[3][4];
arr1[0][0] = 1;
arr1[0][1] = 3;
arr1[0][2] = 5;
arr1[0][3] = 7;
arr1[1][0] = 10;
arr1[1][1] = 11;
arr1[1][2] = 16;
arr1[1][3] = 20;
arr1[2][0] = 23;
arr1[2][1] = 30;
arr1[2][2] = 34;
arr1[2][3] = 50;
int target1 = 16;
int target2 = 13;
int[][] arr2 = new int[1][2];
arr2[0][0] = 1;
arr2[0][1] = 3;
int target3 = 3;
// 測試案例期望值
boolean expResult1 = true;
boolean expResult2 = false;
boolean expResult3 = true;
// 執行方法
Solution074 solution074 = new Solution074();
boolean result1 = solution074.searchMatrix(arr1, target1);
boolean result2 = solution074.searchMatrix(arr1, target2);
boolean result3 = solution074.searchMatrix(arr2, target3);
// 判斷期望值與實際值
Assert.assertEquals(expResult1, result1);
Assert.assertEquals(expResult2, result2);
Assert.assertEquals(expResult3, result3);
}
其他
程式碼託管碼雲地址:https://gitee.com/lizhaoandroid/LeetCodeAll.git
檢視其他內容可以點選專欄或者我的部落格哈:https://blog.csdn.net/cmqwan
“大佬們的答案” 標籤來自leetcode,侵權請聯絡我進行刪改
如有疑問請聯絡,聯絡方式:QQ3060507060