74. Search a 2D Matrix

2018/05/12 leetcode 共 767 字,约 3 分钟

Title

the problem link

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. Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true
Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

以前做过,其实可以参考我的另一个bloglink

Solution

//cpp:
class Solution {
public:
	bool searchMatrix(vector<vector<int>>& matrix, int target) {
		int n = matrix.size();
        if(n==0)
            return false;
		int m = matrix[0].size();
		int i = n - 1,j = 0;
		while (0<=i&&j<m)
		{
			if (matrix[i][j] == target) {
				return true;
			}
			else if (matrix[i][j] < target) {
				j++;
			}
			else {
				i--;
			}
		}
		return false;
	}
};

Search

    Table of Contents