1. 程式人生 > 實用技巧 >劍指office--------二維陣列的查詢

劍指office--------二維陣列的查詢

題目描述

在一個二維陣列中(每個一維陣列的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。 思路1:暴力遍歷
 1 class Solution {
 2 public:
 3     int add(int target, vector<vector<int> > array,int x,int pos){
 4         while (1){
 5             if (array[x].size()<=pos)    return
pos-1; 6 if (array[x][pos]==target){ 7 return -1; 8 } 9 if (array[x][pos]<target){ 10 pos++; 11 continue; 12 } 13 else return pos; 14 } 15 16 17 } 18 int sub(int
target, vector<vector<int> > array,int x,int pos){ 19 while (1){ 20 if (pos<0) return 0; 21 if (array[x][pos]==target) return -1; 22 if (array[x][pos]>target){ 23 pos--; 24 continue; 25 } 26
else return pos; 27 } 28 } 29 bool Find(int target, vector<vector<int> > array) { 30 if (array.size()==0||array[0].size()==0) return false; 31 bool flag=false; 32 int rows=array.size(),col=array[0].size(); 33 for (int i=0,pos=0;i<rows;i++){ 34 if (array[i][pos]==target) return true; 35 else if (array[i][pos]<target){ 36 pos=add(target,array,i,pos); 37 } 38 else pos=sub(target,array,i,pos); 39 if (pos==-1) return true; 40 } 41 return flag; 42 } 43 };

思路2:當找到一個數字大於待查詢的數字時,那麼可以將矩陣進行分割,如圖