題目
在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
題解
一、暴力法
1. 分析
挨個遍歷數組,如果找到就返回 true
2. 代碼
public class Solution {
public boolean Find(int target, int [][] array) {
for(int i=0;i<array.length;i++){
for(int j=0;j<array[0].length;j++){
if(array[i][j] == target){
return true;
}
}
}
return false;
}
}
3. 複雜度
時間複雜度:
空間複雜度:
二、從左下找
1. 分析
利用該二維數組的性質:
- 每一行都按照從左到右遞增的順序排序,
- 每一列都按照從上到下遞增的順序排序
改變個說法,即對於左下角的值 m,m 是該行最小的數,是該列最大的數
每次將 m 和目標值 target 比較:
- 當 m < target,由於 m 已經是該行最大的元素,想要更大隻有從列考慮,取值右移一位
- 當 m > target,由於 m 已經是該列最小的元素,想要更小隻有從行考慮,取值上移一位
- 當 m = target,找到該值,返回 true
用某行最小或某列最大與 target 比較,每次可剔除一整行或一整列
2. 代碼
public class Solution {
public boolean Find(int target, int [][] array) {
int rows = array.length;
if(rows == 0){
return false;
}
int cols = array[0].length;
if(cols == 0){
return false;
}
// 左下
int row = rows-1;
int col = 0;
while(row>=0 && col<cols){
if(array[row][col] < target){
col++;
}else if(array[row][col] > target){
row--;
}else{
return true;
}
}
return false;
}
}
3. 複雜度
時間複雜度:
空間複雜度:
三、從右上找
1. 分析
和從左下找道理一樣,都是因爲每次判斷都能剔除一整行或一整列
2. 代碼
public class Solution {
public boolean Find(int target, int [][] array) {
int rows = array.length;
if(rows == 0){
return false;
}
int cols = array[0].length;
if(cols == 0){
return false;
}
// 右上
int row = 0; //注意
int col = cols-1; //注意
while(row<rows && col>=0){ //注意
if(array[row][col] < target){
row++; //注意
}else if(array[row][col] > target){
col--; //注意
}else{
return true;
}
}
return false;
}
}
3. 複雜度
時間複雜度:
空間複雜度: