zoukankan      html  css  js  c++  java
  • 【leetcode-74】搜索二维矩阵

    (较简单,但犯错太多)

    编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

    • 每行中的整数从左到右按升序排列。
    • 每行的第一个整数大于前一行的最后一个整数。

    示例 1:

    输入:
    matrix = [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    target = 3
    输出: true
    

    示例 2:

    输入:
    matrix = [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    target = 13
    输出: false

    我的:二分,不难但下标转换调试很久
    执行用时 : 1 ms, 在Search a 2D Matrix的Java提交中击败了100.00% 的用户
    内存消耗 : 44.6 MB, 在Search a 2D Matrix的Java提交中击败了0.61% 的用户
        public boolean searchMatrix(int[][] matrix, int target) {
            // 实际遇到其实可以遍历放到数组中二分,这样很简单且题目并没额外要求
            // 数组容易忽略不为空但是为[]的情况所以要判断matrix.length != 0
            if (matrix == null || matrix.length == 0) {
                return false;
            }
            int row = matrix.length;
            int col = matrix[0].length;
            int end = row*col-1;
            int start = 0;
            while (start <= end) {
                int mid = (start + end)/2;
                int val = matrix[mid/col][mid%col];  //0-end数组下标转矩阵下标就是这么简洁,想复杂了
                if (val == target) {
                    return true;
                } else if (val < target) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }
            return false;
        }

    参考解法:比二分慢些但是逻辑简单啊

    执行用时 : 2 ms, 在Search a 2D Matrix的Java提交中击败了100.00% 的用户
    内存消耗 : 41.4 MB, 在Search a 2D Matrix的Java提交中击败了0.61% 的用户
    
    首先选取右上角数字,如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,去掉此数字所在列;如果该数字小于要查找的数字,则去掉该数字所在行。重复上述过程直到找到要查找的数字,或者查找范围为空。
    public boolean searchMatrix(int[][] matrix, int target) {
            if(matrix.length == 0)
                return false;
            int row = 0, col = matrix[0].length-1;
            while(row < matrix.length && col >= 0){
                if(matrix[row][col] < target)
                    row++;
                else if(matrix[row][col] > target)
                    col--;
                else
                    return true;
            }
            return false;
        }
  • 相关阅读:
    poj2386 Lake Counting
    poj 1852 Ants
    Luogu P2419 [USACO08JAN]牛大赛Cow Contest
    Luogu P2336 [SCOI2012]喵星球上的点名
    Luogu P2463 [SDOI2008]Sandy的卡片
    Luogu P2852 [USACO06DEC]牛奶模式Milk Patterns
    Luogu P4248 [AHOI2013]差异
    【NOI2008】志愿者招募
    Luogu P2743 [USACO5.1]乐曲主题Musical Themes
    P3723 [AH2017/HNOI2017]礼物
  • 原文地址:https://www.cnblogs.com/twoheads/p/10646943.html
Copyright © 2011-2022 走看看