LeetCode240. Search a 2D Matrix II题解
来源:互联网 发布:用友软件供应商 编辑:程序博客网 时间:2024/05/26 17:48
题目描述
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 in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.
样例
For example, consider the following 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]
]
Given target = 5, return true;
Given target = 20, return false.
解题思路:
在每行进行二分查找,耗时192ms 比直接暴力查快
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { int BinarySearch(int *array, int aSize, int key) { if ( array == NULL || aSize == 0 ) return -1; int low = 0; int high = aSize - 1; int mid = 0; while ( low <= high ) { mid = (low + high )/2; if ( array[mid] < key) low = mid + 1; else if ( array[mid] > key ) high = mid - 1; else return mid; } return -1; } int i,j,ans; for(i=0;i<matrixRowSize;i++) { ans = BinarySearch(matrix[i],matrixColSize,target); if(ans != -1) { return true; } } return false;}
下面这种解法是看到别人的方法,时间复杂度更低。
上一种是从矩阵左上角开始的,这次从右上角开始。因为这是已经排序好的矩阵,比右上角小的只能在他左边(即行序号–),比右上角大的只能在他的下边(及列序号++)
代码如下:
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { if(matrixRowSize==0 || matrixColSize==0) return false; int i = 0,j = matrixColSize-1; while(i<matrixRowSize && j>=0) { if(target == matrix[i][j]) return true; else if(target < matrix[i][j]) --j; else ++i; } return false; }
阅读全文
0 0
- LeetCode240. Search a 2D Matrix II题解
- LeetCode240. Search a 2D Matrix II题解
- LeetCode240:Search a 2D Matrix II
- leetcode240---Search a 2D Matrix II
- LeetCode240:Search a 2D Matrix II
- Leetcode240: Search a 2D Matrix II
- Leetcode240. Search a 2D Matrix II
- leetcode240. Search a 2D Matrix II
- leetcode240. Search a 2D Matrix II
- LeetCode240——Search a 2D Matrix II
- LeetCode240. Search a 2D Matrix II二分查找+分治法
- leetcode题解-74. Search a 2D Matrix && 240. Search a 2D Matrix II
- LeetCode 题解(149): Search a 2D Matrix II
- Lintcode38 Search a 2D Matrix II solution 题解
- 240. Search a 2D Matrix II 题解
- LeetCode题解:Search a 2D Matrix
- LeetCode题解:Search a 2D Matrix
- Search a 2D Matrix II
- 2年Java开发工作经验面试总结
- Java基础之方法
- 1137 矩阵乘法 基础矩阵乘法
- OMS运维管理平台搭建
- Recyclerview-点击的实现
- LeetCode240. Search a 2D Matrix II题解
- Shortest Prefixes【trie模板题】
- HDU 1429-胜利大逃亡(续)
- C程序在Ubuntu下创建运行
- 网络问题
- sip API日常
- (webservice) apache CXF wsdl2java工具的使用
- 银行本利之和
- 单调栈的运用