仅作为个人笔记
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
C++
class Solution {
public:
bool Find(vector<vector<int> > array,int target) {
int rowCount = array.size();
int colCount = array[0].size();
int i, j;
for(i = rowCount-1,j = 0; i >= 0 && j < colCount;)
{
if(target == array[i][j])
return true;
else if(target < array[i][j])
{
i--;
continue;
}
else
{
j++;
continue;
}
}
return false;
}
};
Java
public class Solution {
public boolean Find(int [][] array,int target) {
int i = array.length - 1;
int j = 0;
while((i >= 0) && (j < array[0].length))
{
if(target == array[i][j])
return true;
else if(target < array[i][j])
i--;
else
j++;
}
return false;
}
}
Python
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, array, target):
# write code here
i = len(array) - 1
j = 0
while((i >= 0) and (j < len(array[0]))):
if(array[i][j] == target):
return True
elif(target < array[i][j]):
i = i - 1
else:
j = j + 1
return False
定位法:先定位到左下角。用左下角元素跟查找元素比较,如果要查找元素小于左下角元素,上移一行,如果大于左下角元素,右移一列。上述方法的时间复杂度为O(m+n)。