1. 程式人生 > >劍指offer演算法題(一)二維陣列中的查詢

劍指offer演算法題(一)二維陣列中的查詢

劍指offer演算法題(一)
題目1:二維陣列中的查詢
在一個二維陣列中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。

思路分析: 
從左上往右下方來解決這個問題 
例如在如下的矩陣中查詢數字27:

6    7    9    10
10    13    19    23
20    27    29    31
26    28    39    40
定義矩陣的行數為 row, 列數為 col; 
設定 i = 0, j = col-1; 
從10開始,當數字小於27時,代表這一行均小於27,這一行其它數字不用再去比較:i++;

10    13    19    23
20    27    29    31
26    28    39    40
此時比較物件變為23,當數字小於27時,代表這一列該數字以下的數字均大於27,無需比較:j–;

10    13    19
20    27    29
26    28    39
比較物件變為19,大於27,i++; 
比較物件變為29,小於27,j–; 
比較物件變為27,等於27==target,返回true;

如果找到最左或最下仍然不匹配,終止尋找,返回false

編寫程式
C++版本

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int row = array.size();
        int col = array[0].size();
        int i = 0;
        int j = col-1;
        while(i<row && j>=0)
        {
            if (array[i][j] == target)
                return true;
            if (array[i][j] > target)
                j--;
            if (array[i][j] < target)
                i++;
        }
        return false;
    }
};

Java版本

public class Solution {
    public boolean Find(int target, int [][] array) {
        int row = array.length;
        int col = array[0].length;
        int i = 0;
        int j = col-1;
        while(i<row && j>=0){
            if(array[i][j] < target)
                i++;
            else if(array[i][j] > target)
                j--;
            else
                return true;
        }
        return false;
    }
}

python版本

# -*- coding:utf-8 -*-
class Solution:
    # array 二維列表
    def Find(self, target, array):
        # write code here
        row = len(array)
        col= len(array[0])
        i = 0
        j = col-1
        while i<row and j>=0:
            if array[i][j] < target:
                i += 1
            elif array[i][j] > target:
                j -= 1
            else:
                return True
        return False

【附】vector基本操作
(1)標頭檔案 #include<vector>.

(2)建立vector物件 vector<int> vec;。vector的元素不僅僅可以是int,double,string,還可以是結構體

(3)尾部插入數字:vec.push_back(a);

(4)使用下標訪問元素,cout<<vec[0]<<endl;,記住下標是從0開始的。

(5)使用迭代器訪問元素.

vector<int>::iterator it;

for(it=vec.begin();it!=vec.end();it++)

    cout<<*it<<endl;

(6)插入元素:

vec.insert(vec.begin()+i,a);//在第i+1個元素前面插入a;

(7)刪除元素:

vec.erase(vec.begin()+2);//刪除第3個元素

vec.erase(vec.begin()+i,vec.end()+j);//刪除區間[i,j-1];區間從0開始

(8)大小 vec.size();(二維vector矩陣的列數:vec[0].size();)

(9)清空 vec.clear();

常見演算法: 
需要標頭檔案 #include<algorithm>

(1) 使用reverse將元素翻轉:reverse(vec.begin(),vec.end()); 
在vector中,如果一個函式中需要兩個迭代器,一般後一個都不包含。

(2)使用sort排序:sort(vec.begin(),vec.end());

預設是按升序排,即從小到大,但可以通過重寫排序比較函式按照降序比較:

bool Comp(const int &a,const int &b)
{
    return a>b;
}
sort(vec.begin(),vec.end(),Comp)

這樣就可以實現降序排序。