[LeetCode] Search a 2D Matrix
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
.
可以参见:http://www.leetcode.com/2010/10/searching-2d-sorted-matrix.html
非常精彩
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int i = 0, j = matrix[0].size() - 1; 7 8 while (i < matrix.size() && j >= 0) 9 { 10 if (target == matrix[i][j]) 11 return true; 12 else if (target < matrix[i][j]) 13 j--; 14 else 15 i++; 16 } 17 18 return false; 19 } 20 };