74. Search a 2D Matrix [LeetCode]

版权声明:QQ:872289455. WeChat:luw9527. https://blog.csdn.net/MC_007/article/details/80998715

74Search 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.

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

矩阵已经排好序,二分搜索

class Solution_74 {
public:
	bool searchMatrix(vector<vector<int>>& matrix, int target) {
		if (matrix.empty())return false;
		const size_t m = matrix.size();
		const size_t n = matrix.front().size();
		if (m==0||n==0||target<matrix[0][0] || target>matrix[m - 1][n - 1])return false;

		int first = 0;
		int last = m * n;
		while (first < last) {
			int mid = first + (last - first) / 2;
			int val = matrix[mid / n][mid%n];
			if (val == target)
				return true;
			else if (val < target)
				first = ++mid;
			else
				last = mid;
		}
		return false;
	}
};



猜你喜欢

转载自blog.csdn.net/MC_007/article/details/80998715