【Leetcode】74. 搜索二维矩阵

266 阅读1分钟

题目描述

在这里插入图片描述

题解

暴力解法

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:38.1 MB, 在所有 Java 提交中击败了7.76%的用户

通过测试用例:133 / 13

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] ints : matrix) {
            for (int i : ints) {
                if (i == target) {
                    return true;
                }
                else if (i > target) {
                    return false;
                }
            }
        }
        return false;
    }
}

贪心算法:

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:38 MB, 在所有 Java 提交中击败了19.72%的用户

通过测试用例:133 / 133

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int i = 0;
        int j = 0;
        int row = matrix.length - 1;
        int col = matrix[0].length - 1;
        while (true) {
            if (matrix[i][j] == target)
                return true;
            else if (i < row && matrix[i + 1][j] <= target)
                i++;
            else if (j < col && matrix[i][j + 1] <= target)
                j++;
            else
                return false;
        }
    }
}

二分查找

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:37.8 MB, 在所有 Java 提交中击败了72.67%的用户

通过测试用例:133 / 133

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length;
        int col = matrix[0].length;
        int left = 0;
        int right = row * col - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            int val = matrix[mid / col][mid % col];
            if (val < target) {
                left = mid + 1;
            }
            else if (val > target) {
                right = mid - 1;
            }
            else {
                return true;
            }
        }
        return false;
    }
}