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

    在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

    public class ld {
        public static void main(String[] args) {
            int[][] array = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
            boolean find = new Solution2().Find(100, array);
            System.out.println(find);
        }
    }
    
    
    class Solution1 {
        /**
         * 暴力法
         *  时间复杂度:O(n^2)
         *  空间复杂度:O(1)
         */
        public boolean Find(int target, int[][] array) {
            for (int i = 0; i < array.length; i++) {
                for (int j = 0; j < array[i].length; j++) {
                    if (array[i][j] == target) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
    
    class Solution2 {
        /**
         * 自下而上,每次排除一行或者一列
         *  时间复杂度:O(行高 + 列宽)
         *  空间复杂度:O(1)
         */
        public boolean Find(int target, int[][] array) {
            int rows = array.length;
            int cols = array[0].length;
            if (rows == 0 || cols == 0) {
                return false;
            }
            int row = rows - 1;
            int col = 0;
            while (row >= 0 && col < cols) {
                if (array[row][col] < target) {
                    col++;
                } else if (array[row][col] > target) {
                    row--;
                } else {
                    return true;
                }
            }
            return false;
        }
    }
    
  • 相关阅读:
    python中的 if __name__ == "__main__": 语句的作用
    python的打包与解包
    python循环删除列表元素
    python字典键值对新增与修改的几种方法及差异总结
    python列表元素删除的几种方法以及差异总结
    python之redis(二)
    python之redis(一)
    python之mysql(四)
    python之mysql(三)
    python之mysql(二)
  • 原文地址:https://www.cnblogs.com/loveer/p/11668086.html
Copyright © 2011-2022 走看看