zoukankan      html  css  js  c++  java
  • 240. Search a 2D Matrix II

    一、题目

      1、审题

      

      2、分析

        给出一个二维数组,每一行的元素、每一列的元素均有序。在此数组中查找 target 元素。

    二、解答

      1、思路

        方法一、

          在每一行中用二分查找法。

        public boolean searchMatrix(int[][] matrix, int target) {
            
            int rows, cols;
            if(matrix == null || (rows = matrix.length) == 0 || (cols = matrix[0].length) == 0)
                return false;
            
            int row = 0;
            while(row < rows) {
                int start = 0, end = cols - 1;
                if(matrix[row][0] > target)
                    return false;
                if(matrix[row][end] < target) {
                    row++;
                    continue;
                }
                while(start <= end) {
                    int mid = (end - start) / 2 + start;
                    if(matrix[row][mid] == target)
                        return true;
                    else if(matrix[row][mid] < target)
                        start = mid + 1;
                    else
                        end = mid - 1;
                }
                row++;
            }
            return false;
        }

      方法二、

        从二维数组的右上角开始向前、向下定位:

        ①、若 target 小于当前元素,则 target 不可能在当前列,因为列向下为升序。

        ②、若 target 大于当前元素,则 target 不可能在当前行,因为当前行为升序。

        public boolean searchMatrix(int[][] matrix, int target) {
            int rows, cols;
            if(matrix == null || (rows = matrix.length) == 0 || (cols = matrix[0].length) == 0)
                return false;
            
            // 从右上角开始查找
            int row = 0, col = cols - 1;
            while(col >= 0 && row < rows) {
                if(target == matrix[row][col])
                    return true;
                else if(target < matrix[row][col])
                    col--;
                else if(target > matrix[row][col])
                    row++;
            }
            return false;
        }
  • 相关阅读:
    c coroutine
    leveldb(ssdb)性能、使用场景评估
    [微信协议分析] 多媒体
    [微信协议分析] 多点登陆
    [微信协议分析] 文本消息
    paxos(chubby) vs zab(Zookeeper)
    分布式一致性算法
    erlang 健壮性
    tcp 出现rst情况整理
    tcp_tw_reuse、tcp_tw_recycle 使用场景及注意事项
  • 原文地址:https://www.cnblogs.com/skillking/p/9942775.html
Copyright © 2011-2022 走看看