[Leetcode学习-java]Search a 2D Matrix

问题:
难度:medium

说明:

在二维数组里面判断是否存在一个元素。

题目连接:

Loading...Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/search-a-2d-matrix/输入范围:

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

输入案例:

Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true

我的代码:

其实是对二维数组做一个二分法搜索即可,先搜索行,再搜索列,要注意搜索行的时候用该行的最小数和最大数作区间比较,然后再继续往下找对应的列。

Java:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0 || matrix[0].length == 0) return false;
        int beginX = 0, endX = matrix.length - 1, midX = (beginX + endX) >> 1;
        
        while(beginX < endX) {
            int midMinV = matrix[midX][0];
            int midMaxV = matrix[midX][matrix[0].length - 1];
            
            if(midMaxV < target) beginX = midX + 1;
            else if(midMinV > target) endX = midX - 1;
            else break;
            
            midX = (beginX + endX) >> 1;
        }
        
        int beginY = 0, endY = matrix[0].length - 1, midY = (beginY + endY) >> 1;
        while(midX >= 0 && midX < matrix.length && beginY < endY) {
            int midV = matrix[midX][midY];
            
            if(midV < target) beginY = midY + 1;
            else if(midV > target) endY = midY - 1;
            else return true;
            
            midY = (beginY + endY) >> 1;
        }
        return midX >= 0 && midY >= 0 && matrix[midX][midY] == target;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值