栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Leetcode】74. 搜索二维矩阵

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Leetcode】74. 搜索二维矩阵

题目描述

题解

暴力解法

执行用时: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;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424146.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号