[LeetCode]74.Search a 2D Matrix,leetcode74.search
【題目】
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.
【思路一】
楊氏矩陣解法:
(1)如果數組中選取的數字剛好和尋找的數字相等,尋找結束,返回true
(2)如果數組中選取的數字小於尋找的數字,根據定序,要尋找的數字只能在當前選取的數位右邊。列數減一。
(3)如果數組中選取的數字大於尋找的數字,根據定序,要尋找的數字只能在當前選取的數位下邊。行數加一。
時間複雜度:O(m+n)
【代碼】
/*------------------------------------ * 日期:2015-02-04 * 作者:SJF0115 * 題目: 74.Search a 2D Matrix * 網址:https://oj.leetcode.com/problems/search-a-2d-matrix/ * 結果:AC * 來源:LeetCode * 部落格: ---------------------------------------*/ #include <iostream> #include <vector> #include <cstring> #include <algorithm> using namespace std; class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if(matrix.empty()){ return false; }//if int row = matrix.size(); int col = matrix[0].size(); int x = 0,y = col - 1; // 楊氏矩陣解法從右上方元素開始 while(x < row && y >= 0){ if(matrix[x][y] == target){ return true; }//if else if(matrix[x][y] < target){ ++x; }//else else{ --y; } }//while return false; } }; int main(){ Solution s; int target = 3; vector<vector<int> > matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,50}}; bool result = s.searchMatrix(matrix,target); // 輸出 cout<<result<<endl; return 0; }
【思路二】根據定序,我們可以把矩陣看成一個串聯起來的一維數組。正好可以利用二分尋找。
n*m矩陣轉換為一維數組:matrix[x][y] -> a[x*m + y]
一維數群組轉換為矩陣:a[x] -> matrix[x / m][ x % m]
時間複雜度:O(nmlognm)【代碼二】
/*------------------------------------ * 日期:2015-02-04 * 作者:SJF0115 * 題目: 74.Search a 2D Matrix * 網址:https://oj.leetcode.com/problems/search-a-2d-matrix/ * 結果:AC * 來源:LeetCode * 部落格: ---------------------------------------*/ class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if(matrix.empty()){ return false; }//if int row = matrix.size(); int col = matrix[0].size(); int start = 0,end = row * col - 1; // 二分尋找解法 int mid,x,y; while(start <= end){ mid = start + (end - start) / 2; x = mid / col; y = mid % col; if(matrix[x][y] == target){ return true; }//if else if(target > matrix[x][y]){ start = mid + 1; }//else else{ end = mid - 1; }//else }//while return false; } };