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;
        }
  • 相关阅读:
    CodeCraft-19 and Codeforces Round #537 (Div. 2) B. Average Superhero Gang Power
    CodeCraft-19 and Codeforces Round #537 (Div. 2) A
    牛客寒假算法基础集训营1 C. 小a与星际探索
    牛客寒假算法基础集训营5 J 炫酷数学
    牛客寒假算法基础集训营5 A 炫酷双截棍
    pat 1136 A Delayed Palindrome
    pta 1140 Look-and-say Sequence (20 分)
    pta 1150 Travelling Salesman Problem (25 分)(模拟)
    2020年团体程序设计天梯赛 L3-1 那就别担心了
    2020年团体程序设计天梯赛 L2-4 网红点打卡攻略
  • 原文地址:https://www.cnblogs.com/twoheads/p/10646943.html
Copyright © 2011-2022 走看看