【LeetCode】搜索二维矩阵2 Search a 2D Matrix II - Medium
2018-02-28 22:34
786 查看
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
” 每行中的整数从左到右是排序的。
” 每一列的整数从上到下是排序的。
” 在每一行或每一列中没有重复的整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
标签
矩阵 Sorted Matrix 谷歌
(1)Java
这个矩阵具有以下特性:
” 每行中的整数从左到右是排序的。
” 每一列的整数从上到下是排序的。
” 在每一行或每一列中没有重复的整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
标签
矩阵 Sorted Matrix 谷歌
(1)Java
package Binary_Search.Search_A_2D_Matrix; public class Search_A_2D_Matrix_II { public class Solution { /** * @param matrix: A list of lists of integers * @param: A number you want to search in the matrix * @return: An integer indicate the occurrence of target in the given matrix */ public int searchMatrix(int[][] matrix, int target) { // check corner case if (matrix == null || matrix.length == 0) { return 0; } if (matrix[0] == null || matrix[0].length == 0) { return 0; } // from bottom left to top right //(curRow,curCol)初始为左下角--> 移动趋势: 向上/右移动 int row = matrix.length, col = matrix[0].length; int curRow = row - 1, curCol = 0; int count = 0; while (curRow >= 0 && curCol < col) { if (matrix[curRow][curCol] < target) { // 此时,该数后面和下面的树均有可能 == target,默认为列优先遍历。 curCol++;// 右移一列 } else if (matrix[curRow][curCol] > target) { //因为此时该数之后的数均 > target, // 则可抛弃当前行 curRow--;// 上移一行 } else {// 即matrix[curRow][curCol] == target, // 由题每行/列的val不重复,则可将当前行&列都抛弃。 count++; curRow--; curCol++; } } return count; } } }
相关文章推荐
- [LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II
- [LeetCode] Search a 2D Matrix II 搜索一个二维矩阵之二
- LeetCode 240. Search a 2D Matrix II (矩阵内搜索)
- [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵
- 240. Search a 2D Matrix II(搜索二维矩阵)
- LeetCode 74. Search a 2D Matrix(搜索二维矩阵)
- 240. Search a 2D Matrix II(搜索二维矩阵之二)
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】
- [Lintcode] Search a 2D Matrix II搜索二维矩阵 II
- [LeetCode] Search a 2D Matrix 搜索一个二维矩阵
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- Leetcode 240. Search a 2D Matrix II[medium]
- (medium)LeetCode 240.Search a 2D Matrix II
- LeetCode | Search a 2D Matrix(二维矩阵中查找)
- [CareerCup] 11.6 Search a 2D Matrix 搜索一个二维矩阵
- LintCode Search a 2D matrix 搜索二维矩阵
- LeetCode 74 Search a 2D Matrix(搜索2D矩阵)
- Leet Code 74 Search a 2D Matrix - 搜索二维矩阵 - Java
- LeetCode OJ 之 Search a 2D Matrix II (二维矩阵查找)