首页 > 其他分享 >leetcode74

leetcode74

时间:2022-11-14 15:56:58浏览次数:38  
标签:20 matrix leetcode74 int 30 60 target

搜索二维矩阵
Category Difficulty Likes Dislikes
algorithms Medium (46.78%) 572 -
Tags
Companies
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

示例 1:
1 3 5 7
10 11 16 20
23 30 34 60

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
示例 2:
1 3 5 7
10 11 16 20
23 30 34 60

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
Discussion | Solution

class Solution {
public:
    // 根据题意,可以将二维转化为一维,然后进行二分
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size(), m = matrix[0].size();
        int l = 0, r = n*m-1;
        while(l <= r)
        {
            int mid = l + ((r-l)>>1);
            int i = mid/m, j=mid%m;
            if(matrix[i][j] == target)
                return true;
            else if(matrix[i][j] < target)
                l = mid + 1;
            else
                r = mid - 1;
        }
        return false;
    }
};

标签:20,matrix,leetcode74,int,30,60,target
From: https://www.cnblogs.com/jinjidelei/p/16889245.html

相关文章

  • leetcode744
    寻找比目标字母大的最小字母Category Difficulty Likes Dislikesalgorithms Easy(45.91%) 249 -TagsCompanies给你一个排序后的字符列表letters,列表中只包含小写英......
  • LeetCode740 删除并获得点数
    LeetCode740删除并获得点数LeetCode198打家劫舍的变形题目classSolution:defdeleteAndEarn(self,nums:List[int])->int:maxVal=max(nums)......