zoukankan      html  css  js  c++  java
  • 剑指Offer04.二维数组中的查找

    题目链接:二维数组中的查找

    思路:二维矩阵数值分布特点是左上角高,右下角低。如果从最高处或最低处开始搜索,那么搜寻路径会很多。而从矩阵右上角开始搜索的话,可以发现,右上角的左边都是递减,下边是递增,那么,从左上角出发,比target大时,就走左边;比target小时就走下边,直到找到target或者走出矩阵范围。同理从左下角出发也可以。

    代码:

    class Solution {
        public boolean findNumberIn2DArray(int[][] matrix, int target) {
            if(matrix.length == 0) return false;
            for(int x = 0, y = matrix[x].length-1; x>=0 && y>=0 && x<matrix.length && y<matrix[x].length;){
                if(matrix[x][y] == target) return true;
                if(matrix[x][y] < target) x ++;
                else y --;
            }
            return false;
        }
    }
    

    执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:44 MB, 在所有 Java 提交中击败了90.04%的用户

  • 相关阅读:
    洛谷 P4317
    洛谷 P6218
    洛谷 P4999
    洛谷 P2657
    CSP 2020-S2 题解
    2020CSP-S2游记
    Spring Boot中使用WebSocket总结
    防盗链
    JVM JRE和JDK的区别和联系
    Java 注解学习
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14209283.html
Copyright © 2011-2022 走看看