leetcode_Search a 2D Matrix II
来源:互联网 发布:十分钟学会python 编辑:程序博客网 时间:2024/05/21 06:43
描述:
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
.
思路:
本题有两种思路,首先想到的是对该矩阵的每一行做二分查找,后来跟人探讨时才知道还有另外一种O(n)时间复杂的方法,下面就细说下这个O(n)时间复杂度的方法
1.首先从第一行的最后一个开始,假设该值为x,当x大于target的时候,那target肯定小于该列的其它值,因为该列是递增的,colNum--;
2.同理,如果target大于x的时候,说明target大于该行的其它值,因为改行也是递增的,即rowNum++;
3.由于每次以一行的速度来排除,所以O(n)的时间复杂度既可以解决该问题。
代码:
O(nlogn)的方法,对每一行进行二分查找
public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null) return false; int endIndex=0; if(matrix[matrix.length-1][matrix[0].length-1]<target)//判断最大的是否小于target return false; for(int i=0;i<matrix.length;i++)//判断要查找的范围 { if(matrix[i][0]>target) { endIndex=i; break; } } if(matrix[matrix.length-1][0]<=target) endIndex=matrix.length; for(int i=0;i<endIndex;i++)//对每一维应用二分查找 { if(binarySearch(matrix[i],target)) return true; } return false; } public boolean binarySearch(int []arr,int target)//二分查找 { int start=0,end=arr.length-1,mid=0; while(start<=end) { mid=(start+end)/2; if(arr[mid]==target) return true; else if(arr[mid]>target) end=mid-1; else start=mid+1; } return false; }
O(N)时间复杂度的解法
public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null) return false; int endIndex=matrix.length; int rowNum=0,columNum=matrix[0].length-1; while(rowNum<endIndex&&columNum>=0) { if(matrix[rowNum][columNum]==target) return true; else if(matrix[rowNum][columNum]<target) rowNum++; else if(matrix[rowNum][columNum]>target) columNum--; } return false; }
0 0
- leetcode_Search a 2D Matrix II
- Leetcode_search-a-2d-matrix
- leetcode_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
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- Search a 2D Matrix II
- 240Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Search a 2D Matrix II
- Search a 2D Matrix II
- Search a 2D Matrix II
- poj1141Brackets Sequence【区间dp+路径记录】
- 带头尾和动画的下拉刷新RecyclerView
- hdu 1072 Nightmare
- [HDU 1011] Starship Troopers 树形dp
- 普通方法求素数与筛法求素数比较
- leetcode_Search a 2D Matrix II
- 简单性能测试函数模板
- C++ std::tr1::function使用
- 关于 RTOS 的选择 (上)
- 机房收费——组合查询的日期和时间的选择实现
- SDNU 1167.花生采摘【NOIP 2004 普及组】【贪心】【8月6】
- Kaggle 机器学习竞赛冠军及优胜者的源代码汇总
- 12170 - Easy Climb(DP+单调队列)
- MCS 最短路#4 SPFA