LeetCode 74. Search a 2D Matrix

Posted Shendu.cc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 74. Search a 2D Matrix相关的知识,希望对你有一定的参考价值。

题目

二分查找

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        if(matrix.size()==0)
            return false;
        if(matrix[0].size()==0)
            return false;
        int right = matrix.size() * matrix[0].size()-1;
        
        int left=0;
        
        while(left < right)
        {
            int mid = (left+right)/2;
            
            int x = mid / matrix[0].size();
            int y = mid % matrix[0].size();
            
            
            if(target > matrix[x][y])
            {
                left = mid + 1;
            }
            if(target == matrix[x][y])
            {
                return true;
            }
            if(target < matrix[x][y])
            {
                right = mid - 1;
            }
        }
        
        int x = left / matrix[0].size();
        int y = left % matrix[0].size();
        
        if(matrix[x][y] == target)
            return true;
        
        
        return false;      
        
    }
};

以上是关于LeetCode 74. Search a 2D Matrix的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 74: Search a 2D Matrix

leetcode 74 Search a 2D Matrix ----- java

LeetCode 74.Search a 2D Matrix Java

LeetCode 74. Search a 2D Matrix

19.2.13 [LeetCode 74] Search a 2D Matrix

一天一道LeetCode#74. Search a 2D Matrix