74. 搜尋二維矩陣

小小小楚楚發表於2020-12-26

74. 搜尋二維矩陣

思路:二分法
將二維陣列展開成一維的再二分就可以

/*
思路:二分查詢	
*/
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
	int m = matrix.size();
	int n = matrix[0].size();
	if (m * n == 0) {
		return false;
	}

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

相關文章