zoukankan      html  css  js  c++  java
  • 搜索二维矩阵

    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.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/search-a-2d-matrix
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    要求在一个二维矩阵找出目标数。借鉴其中一个题解的做法,从右上角开始遍历,目标数比右上角的数大,证明不在当前一行,行数+1;目标数比右上角的数小,证明不在当前一列,列数-1:

        public boolean searchMatrix(int[][] matrix, int target) {
            if(matrix == null || matrix.length == 0)
            {
                return false;
            }
            int row = 0;
            int col = matrix[0].length - 1;
            int length = matrix.length;
            while(row < length && col >= 0)
            {
                if(matrix[row][col] == target)
                {
                    return true;
                }
                else if(matrix[row][col] < target)
                {
                    row++;
                }
                else
                {
                    col--;
                }
            }
            return false;
        }
  • 相关阅读:
    1-4 Autolayout
    1-3 UIScrollView
    lua 的语法糖
    javascript文档
    cocos2d 图片模糊
    a*寻路分析
    class按传递时分析
    mac 不再接受预览版提示
    OS X 10.11 El Capitan 三指拖动的开启方法
    mac系统卸载mono
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/11518217.html
Copyright © 2011-2022 走看看