240. Search a 2D Matrix II
- Total Accepted: 64544
- Total Submissions: 169839
- Difficulty: Medium
- Contributors: Admin
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]
Given target = 5
, return true
.
Given target = 20
, return false
.
Solution:
1 class Solution { 2 public: 3 //我们可以发现有两个位置的数字很有特点,左下角和右上角的数。左下角的18,往上所有的数变小,往右所有数增加,那么我们就可以和目标数相比较,如果目标数大,就往右搜,如果目标数小,就往左搜。这样就可以判断目标数是否存在。当然我们也可以把起始数放在右上角,往左和下搜,停止条件设置正确就行。 4 bool searchMatrix(vector<vector<int>>& matrix, int target) { 5 if(matrix.size() == 0 || matrix[0].size() == 0) return false; 6 int m = matrix.size(); 7 int n = matrix[0].size(); 8 if(target < matrix[0][0] || target > matrix[m - 1][n - 1]) return false; 9 int x = m - 1; 10 int y = 0; 11 while(true){ 12 if(target < matrix[x][y]){ 13 x --; 14 }else if(target > matrix[x][y]){ 15 y ++; 16 }else if(target == matrix[x][y]){ 17 return true; 18 } 19 if(x < 0 || y >= n) break; 20 } 21 return false; 22 } 23 };