[劍指Offer]5.二維數組中的尋找,劍指offer

來源:互聯網
上載者:User

[劍指Offer]5.二維數組中的尋找,劍指offer

題目

在一個二維數組中,每一行都按照從左至右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。

思路

[演算法系列之三十三]楊氏矩陣

代碼

/*---------------------------------------*   日期:2015-07-19*   作者:SJF0115*   題目: 5.二維數組中的尋找*   網址:http://www.nowcoder.com/books/coding-interviews/abc3fe2ce8e146608e868a70efebf62e?rp=1*   結果:AC*   來源:劍指Offer*   部落格:-----------------------------------------*/#include <iostream>#include <vector>using namespace std;class Solution {public:    bool Find(vector<vector<int> > array,int target) {        int row = array.size();        if(row == 0){            return false;        }//if        int col = array[0].size();        if(col == 0){            return false;        }//if        int i = 0,j = col - 1;        while(i < row && j >= 0){            // 大於目標 剔除這個數字所在的列            if(array[i][j] > target){                --j;            }//if            // 小於目標 剔除這個數字所在的行            else if(array[i][j] < target){                ++i;            }//else            else{                return true;            }//else        }//while        return false;    }};int main(){    Solution s;    vector<vector<int> > matrix = {            {1,4,7,11,15},            {2,5,8,12,19},            {3,6,9,16,22},            {10,13,14,17,24},            {18,21,23,26,30}        };    int target = 30;    cout<<s.Find(matrix,target)<<endl;    return 0;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.