劍指offer:二維數組中的查找
在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。
請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
//思路:首先選一個右上角的元素,當target大於這個元素,說明不在這一行,直接下一行(排除此行)(i++)
// 當target小於這個元素,說明這一列向下都沒有,找前一列(排除此列) j--
ac代碼:
class Solution { public: //思路:首先選一個右上角的元素,當target大於這個元素,說明不在這一行,直接下一行(i++) // 當target小於這個元素,說明這一列向下都沒有,找前一列 j-- bool Find(int target, vector<vector<int>> &array) { int row = array.size(); //行 int col = array[0].size(); // 列 int i = 0, j = col-1; // j是最后一列 // bool flag = false; while(i < row && j >= 0) { if (target == array[i][j]) { return true; } else if (target > array[i][j]) // 大於前行的最后一個,說明不在這一行i++ { i++; } else if (target < array[i][j]) // 小於當前行的最后一個,說明不在這一列,j-- { j--; } } return false; } };
加上main函數的版本

1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 // 判斷當前行的最后一個數是否大於目標值, 5 //如果大於則當前行不存在,進入下一行 6 class Solution { 7 public: 8 bool Find(int target, vector<vector<int> > &array) { 9 int row = array.size(); // 行 10 int col = array[0].size(); // 列 11 12 13 for(int i = 0; i < row; i++) 14 { 15 if (target > array[i][col-1]) 16 continue; 17 for( int j = 0; j < col; j++) 18 { 19 if (target == array[i][j]) 20 { 21 return true; 22 } 23 } 24 } 25 return false; 26 27 } 28 29 //思路:首先選一個右上角的元素,當target大於這個元素,說明不在這一行,直接下一行(i++) 30 // 當target小於這個元素,說明這一列向下都沒有,找前一列 j-- 31 bool find2(int target, vector<vector<int>> &array) 32 { 33 int row = array.size(); //行 34 int col = array[0].size(); // 列 35 int i = 0, j = col-1; // j是最后一列 36 // bool flag = false; 37 38 while(i < row && j >= 0) 39 { 40 if (target == array[i][j]) 41 { 42 return true; 43 } 44 else if (target > array[i][j]) // 大於前行的最后一個,說明不在這一行i++ 45 { 46 i++; 47 } 48 else if (target < array[i][j]) // 小於當前行的最后一個,說明不在這一列,j-- 49 { 50 j--; 51 } 52 } 53 return false; 54 } 55 }; 56 int main() 57 { 58 Solution s; 59 int t = 1; 60 vector<vector<int> > arra(4,vector<int>(3,0)); // 4行三列 61 for (int i = 0; i < 4; i++) 62 { 63 for (int j = 0; j < 3; j++) 64 { 65 arra[i][j] = t++; 66 } 67 } 68 for (int i = 0; i < 4; i++) 69 { 70 for (int j = 0; j < 3; j++) 71 { 72 cout << arra[i][j]<<" "; 73 } 74 cout << endl; 75 } 76 77 cout << endl; 78 bool falg = s.find2(40, arra); 79 cout << falg; 80 81 return 0; 82 } 83 //std::vector<std::vector<int> > vec(row,vector<int>(col,0)); 84 //初始化row * col二維動態數組,初始化值為0