题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
# -*- coding:utf-8 -*- class Solution: # array 二维列表 def Find(self, target, array): # write code here row=len(array)-1 col=len(array[0])-1 i=row j=0 while i>=0 and j<=col: if target<array[i][j]: i-=1 elif target>array[i][j]: j+=1 else: return True return False
开始刷题,每天一至二道,不要断。同时看《Accelerated C++》。前面讲c++语法的都没看懂,先从这看起吧。注意细节。
其中由于len(array),len(array[1])都等于4(A=[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]),所以都需要-1。
疑问,使用类方法的函数第一个参数为(self)。什么是类方法?为什么要用self?
顺便把c++的贴在下面:
class
Solution {
public
:
bool
Find(
int
target, vector<vector<
int
> > array) {
// array是二维数组,这里没做判空操作
int
rows = array.size();
int
cols = array[0].size();
int
i=rows-1,j=0;
//左下角元素坐标
while
(i>=0 && j<cols){
//使其不超出数组范围
if
(target<array[i][j])
i--;
//查找的元素较少,往上找
else
if
(target>array[i][j])
j++;
//查找元素较大,往右找
else
return
true
;
//找到
}
return
false
;
}
};
和
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
;
}
}
主要是标黄的看不懂,下面还有一个用遍历做的。
把每一行看成有序递增的数组,
利用二分查找,
通过遍历每一行得到答案,
时间复杂度是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
;
}
}