题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
时间限制:1秒 空间限制:32768K简单方法:二维数组遍历
二维数组遍历:python版本
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
for rows in array:
for i in rows:
if target == i:
return True
return False
满足要求
二维数组遍历:java版本
public class Solution {
public boolean Find(int target, int [][] array) { //返回boolean类型
boolean result = false; //事先创建boolean类型变量
for(int i = 0 ;i < array.length; i++){ //外层控制列数
for(int j = 0; j < array[i].length; j++){ //内层控制行数
if( target == array[i][j]){
result = true; //注意不能在此处return,作为小白的我搞了很久
break;
}
}
}
return result;
}
}
满足要求
二维数组遍历:c++版本
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
bool result = false;
if (array.empty()){
cout << "The vector is empty!" << endl;
return false;
}
int i,j;
for (i = 0; i < array.size(); i++){
for (j = 0; j < array[0].size(); j++){
if (target == array[i][j]){
result = true;
break;
}
}
}
return result;
}
};
很快
思路2:因为数组从上到下递增,从左到右递增,所以从左下角找(i,j分别代表行、列)
如果target大,则往右找 j++
如果target小,则往上找 i--
思路2:java版
/*
* 思路2:数组从上到下递增,从左到右递增,所以从左下角找
* 如果target大,则往右找j++
* 如果target小,则往上找i--
*/
public class Solution {
public boolean Find(int target, int [][] array) {
int rows = array.length; //数组行数
int columns = array[0].length; //数组列数
int i,j; //i表示行数,j表示列数
for ( i = rows-1,j = 0 ; i>=0 && j < columns ; ) { // 不能 i<0 || j>= columns
if (target == array[i][j]){
return true; //为什么这里又可以在if里 return ??
} else if (target < array[i][j]) {
i--;
continue;
} else if (target > array[i][j]) {
j++;
continue;
}
}
return false;
}
}
差不多与二维数组遍历一样性能
思路2:C++版
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
/*二维数组的行数和列数*/
int rowCount = array.size();
int colCount = array[0].size();
int i, j;//i指定行的变化,j指定列的变化
//循环
for (i = rowCount - 1, j = 0; i >= 0 && j<colCount;)
{
if (target == array[i][j])
return true;
if (target<array[i][j])
{
i--;
continue;
}
if (target>array[i][j])
{
j++;
continue;
}
}
return false;
}
};
反而比数组遍历方法慢了一点。