牛客《剑指Offer》 二维数组中的查找
来源:互联网 发布:淘宝多店铺管理软件 编辑:程序博客网 时间:2024/06/04 23:39
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:从左下角开始搜索,如果当前数大于target ,向下移动,如果当前数小于target ,向后移动。
class Solution {public: bool Find(int target, vector<vector<int> > array) { int vrow = array.size(); int vcol = array[0].size(); int tmprow = vrow-1; int tmpcol = 0; while(1){ if(tmprow == -1 || tmpcol == vcol){ return false; } else if(array[tmprow][tmpcol] == target){ return true; } else if(array[tmprow][tmpcol] < target){ tmpcol++; } else{ tmprow--; } } }};
论坛思路:2种
1.把每一行看成有序递增的数组,
利用二分查找,
通过遍历每一行得到答案,
时间复杂度是nlogn
public
class
Solution {
public
boolean
Find(
int
[][] array,
int
target) {
for
(
int
i=
0
;i<array.length;i++){
int
low=
0
;
int
high=array[i].length-
1
;
while
(low<=high){
int
mid=(low+high)/
2
;
if
(target>array[i][mid])
low=mid+
1
;
else
if
(target<array[i][mid])
high=mid-
1
;
else
return
true
;
}
}
return
false
;
}
}
2.另外一种思路是:
利用二维数组由上到下,由左到右递增的规律,
那么选取右上角或者左下角的元素a[row][col]与target进行比较,
当target小于元素a[row][col]时,那么target必定在元素a所在行的左边,
即col--;
当target大于元素a[row][col]时,那么target必定在元素a所在列的下边,
即row++;
public
class
Solution {
public
boolean
Find(
int
[][] array,
int
target) {
int
row=
0
;
int
col=array[
0
].length-
1
;
while
(row<=array.length-
1
&&col>=
0
){
if
(target==array[row][col])
return
true
;
else
if
(target>array[row][col])
row++;
else
col--;
}
return
false
;
}
}
2.
阅读全文
0 0
- 牛客《剑指Offer》 二维数组中的查找
- 剑指offer-->二维数组中的查找
- 剑指offer之二维数组中的查找
- 剑指offer:3-二维数组中的查找
- [剑指Offer]二维数组中的查找
- 【剑指offer】二维数组中的查找
- [剑指Offer]二维数组中的查找
- 剑指Offer:二维数组中的查找
- 【剑指offer】二维数组中的查找
- 剑指offer 1384 二维数组中的查找
- 剑指Offer之二维数组中的查找
- 剑指offer 03:二维数组中的查找
- 剑指offer(2) - 二维数组中的查找
- 剑指offer-二维数组中的查找
- 剑指offer-3 二维数组中的查找
- 剑指Offer之 - 二维数组中的查找
- 剑指offer 3 -二维数组中的查找
- 剑指offer之二维数组中的查找
- 多个对象无锁
- Java多线程基础
- Leetcode 338Counting Bits
- 详解Spring中bean的scope
- 重写(override)和重载(overload)的区别
- 牛客《剑指Offer》 二维数组中的查找
- [BZOJ]4403: 序列统计 Lucas定理
- python+caffe训练自己的图片数据流程
- 使用java操作Excel
- css设置透明度不影响子元素
- iOS: FFmpeg的使用一
- jzoj5167 【NOIP2017模拟6.26】下蛋爷 [ac自动机,概率递推]
- Redis之事务
- B. Valued Keys