38.Search a 2D Matrix II-搜索二维矩阵 II(中等题)
来源:互联网 发布:软件培训学校哪家好 编辑:程序博客网 时间:2024/05/22 08:26
翻转字符串
题目
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。样例
考虑下列矩阵:
给出target = 3,返回 2挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
题解
采用分治法的思想,从矩阵右上角开始遍历,
如果matrix[i][j]等于target,则所在行列就不用再查找了;
如果matrix[i][j]大于target,则所在列就不用再查找了;
如果matrix[i][j]小于target,则所在行就不用再查找了;
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) { if (matrix.length == 0) { return 0; } int i = 0; int j = matrix[0].length-1; int count = 0; while (i < matrix.length && j >= 0) { if (matrix[i][j] == target) { count++; ++i; --j; } else if (matrix[i][j] < target) { ++i; } else if (matrix[i][j] > target) { --j; } } return count; }}
Last Update 2016.9.26
0 0
- 38.Search a 2D Matrix II-搜索二维矩阵 II(中等题)
- Search a 2D Matrix II(搜索一个二维矩阵)
- 240. Search a 2D Matrix II(搜索二维矩阵)
- 第三周:240. Search a 2D Matrix II(搜索二维矩阵之二)
- [Lintcode] Search a 2D Matrix II搜索二维矩阵 II
- LeetCode OJ 之 Search a 2D Matrix II (二维矩阵查找)
- LeetCode 240. Search a 2D Matrix II (矩阵内搜索)
- leetcode 240. Search a 2D Matrix II 矩阵搜索 + 右上角搜索
- 28.Search a 2D Matrix-搜索二维矩阵(容易题)
- LintCode Search a 2D matrix 搜索二维矩阵
- 381.Spiral Matrix II-螺旋矩阵 II(中等题)
- LeetCode OJ 之 Search a 2D Matrix (二维矩阵的搜索)
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】
- Search a 2D Matrix II
- [刷题]Search a 2D Matrix II
- lintcode:Search a 2D Matrix II
- #leetcode#Search a 2D Matrix II
- Search a 2D Matrix II
- SQLServer与MySQL的比较
- Linux-xargs命令
- 新一代“蓝氧净血自体免疫调节”成果转化技术发布会倒计时5天
- charles的使用教程
- git
- 38.Search a 2D Matrix II-搜索二维矩阵 II(中等题)
- 1212
- 怎样利用好异常处理机制?
- 开发日志-ITS Android版本 综述
- 关于本地缓存localstorage与sessionStorage 数组 (array)字符串(string) 对象(object)的存储技巧和注意事项
- 12523
- Linux的文件管理命令和bash工作特性
- 25454
- 36.Reverse Linked List II-翻转链表 II(中等题)