Leetcode 240:搜索二维矩阵II

搜索二维矩阵II

题目描述

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

示例

现有矩阵 matrix 如下:
    [
        [1,   4,  7, 11, 15],
        [2,   5,  8, 12, 19],
        [3,   6,  9, 16, 22],
        [10, 13, 14, 17, 24],
        [18, 21, 23, 26, 30]
    ]
给定 target = 5,返回 true。
给定 target = 20,返回 false。

思路

思路1 暴力法

直接二维数组遍历

思路2: 按照已有顺序遍历

按照题目给的信息,则可根据原数组的排序方式,设置index从数组第一行最后一列元素开始遍历,这样以m+n的算法复杂度得出结果

代码

思路2:代码

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rows = matrix.length;
        int columns = matrix[0].length;
        int rowIndex = 0;
        int colIndex = columns - 1;
        boolean result = false;

        while (rowIndex < rows && colIndex >= 0) &#123;
            while (rowIndex < rows && colIndex >= 0 && matrix[rowIndex][colIndex] > target) &#123;
                colIndex --;
            &#125;
            while (rowIndex < rows && colIndex >= 0 && matrix[rowIndex][colIndex] < target) &#123;
                rowIndex ++;
            &#125;
            if (rowIndex < rows && colIndex >= 0 && target == matrix[rowIndex][colIndex]) &#123;
                result = true;
                break;
            &#125;
        &#125;
        return result;
    &#125;
&#125;

总结体会

在实现过程中需要注意下标溢出


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:169. 多数元素 Leetcode:169. 多数元素
多数元素题目描述给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 示例示例1: 输入: [3,2,3]
2020-03-05
下一篇 
LeetCode 32:最长有效括号 LeetCode 32:最长有效括号
最长有效括号题目描述给定一个只包含 ‘(‘ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。 示例1:输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()" 示例2:输入:
2020-03-04
  目录