题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:
从右上角/左下角开始处理,
如果大于就不在这个列,y--;
如果小于就不在这个行,x++;
如果等于返回true
坑:
x,y都能够等于0。
边界条件要判断好。
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
bool found=false;
if(array.size()==0||array[0].size()==0)
return false;
int x=0;//row
int y=array[0].size()-1;//line
while(x<array.size()&&y>=0)
{
if(array[x][y]==target)
return true;
else if(array[x][y]>target){
if(y>=0){
y--;}}
else{
++x;
}
}
return found;
}
};
调试代码:
#include <iostream>
#include <vector>
using namespace std;
bool Find(int target, vector<vector<int> > array) {
bool found=false;
if(array.size()==0||array[0].size()==0)
return false;
int x=0;//row
int y=array[0].size()-1;//line
while(x<array.size()&&y>=0)
{
if(array[x][y]==target)
return true;
else if(array[x][y]>target){
if(y>=0){
y--;}}
else{
++x;
}
}
return found;
}
int main()
{
vector<vector<int>> v;
int array[4][4]={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
for (int i=0;i<4;i++)
{
vector<int> tmp(array[i],array[i]+4);
v.push_back(tmp);
}
bool res=Find(7,v);
cout<<res<<endl;
return 0;
}
java实现:
public class first {
public static boolean Find(int target, int[][] array) {
/**
* array[0]是一个指针,只需要判断array[0]就可以了,不需要判断array.length
*/
if (array[0].length==0){
return false;
}
int col = array[0].length - 1;
int line = array.length - 1;
int i = line;
int j = 0;
do {
if (array[i][j] == target) {
return true;
} else if (array[i][j] > target) {
i--;
} else {
j++;
}
} while (i >= 0 && j <= col);
return false;
}
public static void main(String[] args) {
int[][] array = {{}};
System.out.println(Find(15, array));
}
}