搜索二维矩阵-数组74-python&c++

二分查找

python

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int):
        m = len(matrix)
        n = len(matrix[0])

        for line in matrix:
            if target < line[0] or target > line[-1]:
                continue
            else:
                left, right = 0, n-1
                while left <= right:
                    mid = int((left + (right-left)/2))

                    if line[mid] == target:
                        return True
                    elif line[mid] < target:
                        left = mid + 1
                    elif line[mid] > target:
                        right = mid - 1
        
        return False

c++

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        // 先定位到某行,就可以砍掉一半元素,再在该行中二分查找
        int row = matrix.size(), column = matrix[0].size();
        int up = 0, down = row - 1;
        int left = 0, right = column - 1;
        
        // 定位到某行
        while (up <= down) {
            int mid = up + (down - up) / 2;
            if (matrix[mid][0] == target) {
                return true;
            } else if (matrix[mid][0] > target) {
                down = mid - 1;
            } else if (matrix[mid][0] < target) {
                up = mid + 1;
            }
        }
        // 边界溢出判断
        if (up > row || down < 0) return false;

        // 此时up为第一列元素中大于target的最小元素的行索引
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (matrix[up-1][mid] == target) {
                return true;
            } else if (matrix[up-1][mid] > target) {
                right = mid - 1;
            } else if (matrix[up-1][mid] < target) {
                left = mid + 1;
            }
        }

        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值