[LeetCode] Search a 2D Matrix 搜尋一個二維矩陣
阿新 • • 發佈:2018-12-27
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
這道題要求搜尋一個二維矩陣,由於給的矩陣是有序的,所以很自然的想到要用二分查詢法,我們可以在第一列上先用一次二分查詢法找到目標值所在的行的位置,然後在該行上再用一次二分查詢法來找是否存在目標值,程式碼如下:
// Two binary search class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; if (target < matrix[0][0] || target > matrix.back().back()) return false; int left = 0, right = matrix.size() - 1; while (left <= right) { int mid = (left + right) / 2; if (matrix[mid][0] == target) return true; else if (matrix[mid][0] < target) left = mid + 1; else right = mid - 1; } int tmp = right; left = 0; right = matrix[tmp].size() - 1; while (left <= right) { int mid = (left + right) / 2; if (matrix[tmp][mid] == target) return true; else if (matrix[tmp][mid] < target) left = mid + 1; else right = mid - 1; } return false; } };
當然這道題也可以使用一次二分查詢法,如果我們按S型遍歷該二維陣列,可以得到一個有序的一維陣列,那麼我們只需要用一次二分查詢法,而關鍵就在於座標的轉換,如何把二維座標和一維座標轉換是關鍵點,把一個長度為n的一維陣列轉化為m*n的二維陣列(m*n = n)後,那麼原一維陣列中下標為i的元素將出現在二維陣列中的[i/n][i%n]的位置,有了這一點,程式碼很好寫出來了:
// One binary search class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; if (target < matrix[0][0] || target > matrix.back().back()) return false; int m = matrix.size(), n = matrix[0].size(); int left = 0, right = m * n - 1; while (left <= right) { int mid = (left + right) / 2; if (matrix[mid / n][mid % n] == target) return true; else if (matrix[mid / n][mid % n] < target) left = mid + 1; else right = mid - 1; } return false; } };