Search a 2D Matrix

/*
 本算法答案由上岸科技提供。
 上岸科技是一个专致力于高效培养北美留学生拥有实际面试能力的团体。
 我们采用小班化线上,线下教学让学生更快,更好的学习到想要的知识。
 团队主要由一群怀揣情怀于美国高校毕业的一线IT公司工程师构成。
 我们坚信对于求职者算法并不是全部,合理的技巧加上适当的算法培训能够大大的提升求职成功概率也能大大减少刷题的痛苦。
 正如我们的信仰:我们教的是如何上岸而不仅是算法。
 更多信息请关注官网:https://www.shanganonline.com/
*/
public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return false;
        int start = 0;
        int end = matrix.length * matrix[0].length - 1;
        int row = 0;
        int col = 0;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            row = mid / matrix[0].length;
            col = mid % matrix[0].length;
            if (matrix[row][col] == target)
                return true;
            if (matrix[row][col] < target)
                start = mid;
            else
                end = mid;
        }
        
        if (matrix[start / matrix[0].length][start % matrix[0].length] == target || 
            matrix[end / matrix[0].length][end % matrix[0].length] == target)
            return true;
        return false;
    }
}

Last updated

Was this helpful?