• leetcode — search-a-2d-matrix


    /**
     * Source : https://oj.leetcode.com/problems/search-a-2d-matrix/
     *
     *
     * Write an efficient algorithm that searches for a value in an m x n matrix.
     * This matrix has the following properties:
     *
     * Integers in each row are sorted from left to right.
     * The first integer of each row is greater than the last integer of the previous row.
     *
     * For example,
     *
     * Consider the following matrix:
     *
     * [
     *   [1,   3,  5,  7],
     *   [10, 11, 16, 20],
     *   [23, 30, 34, 50]
     * ]
     *
     * Given target = 3, return true.
     *
     */
    public class SearchMatrix {
    
        /**
         * 因为矩阵是连续有序的,所以可以当做一维数组处理,使用二分法搜索
         * 也可以使用二分法先搜索第一列,确定处于哪一行,再对该行使用二分法搜索
         *
         *
         *
         * @return
         */
        public boolean search (int[][] matrix, int target) {
            if (matrix.length == 0 || matrix[0].length == 0) {
                return false;
            }
            int m = matrix.length;
            int n = matrix[0].length;
            int left = 0;
            int right = m * n;
            int mid = (left + right) / 2;
            int midi = mid / n;
            int midj = mid % n;
            while (left <= right) {
                if (matrix[midi][midj] == target) {
                    return true;
                }
                if (matrix[midi][midj] > target) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
                mid = (left + right) / 2;
                midi = mid / n;
                midj = mid % m;
            }
            return false;
        }
    
    
        public static void main(String[] args) {
            SearchMatrix searchMatrix = new SearchMatrix();
            int[][] matrix = new int[][]{
                    {1,   3,  5,  7},
                    {10, 11, 16, 20},
                    {23, 30, 34, 50}
            };
            System.out.println(searchMatrix.search(matrix, 3));
            System.out.println(searchMatrix.search(matrix, 11));
            System.out.println(searchMatrix.search(matrix, 34));
            System.out.println(searchMatrix.search(matrix, 0));
    
        }
    }
    
  • 相关阅读:
    SqlDependency和SqlCacheDependency的若干说明
    sublime 3 随笔
    [有得]解决redmine写操作很慢的问题
    Java双重循环
    使用 Docker 打包 Rust Web 服务
    Centos8.3、hadoop-2.6.4 简单的日志分析实验
    广域网数据交换的三种方式
    计算机的起源与发展
    推荐两款生成数据库表结构说明文档工具
    Centos8.3、docker部署springboot项目实战记录
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7727002.html
Copyright © 2020-2023  润新知