编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
示例 1:
输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 输出: true
示例 2:
输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 输出: false
//搜索二维矩阵 class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { //行数 int m = matrix.size(); if (m == 0) return false; //列数 int n = matrix[0].size(); // 二分查找 //right 是总长 int left = 0, right = m * n - 1; int pivotIdx, pivotElement; while (left <= right) { pivotIdx = (left + right) / 2; //把总长的中间值转化为行和列 pivotElement = matrix[pivotIdx / n][pivotIdx % n]; if (target == pivotElement) return true; else { if (target < pivotElement) right = pivotIdx - 1; else left = pivotIdx + 1; } } return false; } };
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/sou-suo-er-wei-ju-zhen-by-leetcode/