二維數組中的尋找[題目2],二維數組尋找題目2

來源:互聯網
上載者:User

二維數組中的尋找[題目2],二維數組尋找題目2

題目描述:

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

輸入:

輸入可能包含多個測試範例,對於每個測試案例,

輸入的第一行為兩個整數m和n(1<=m,n<=1000):代表將要輸入的矩陣的行數和列數。

輸入的第二行包括一個整數t(1<=t<=1000000):代表要尋找的數字。

接下來的m行,每行有n個數,代表題目所給出的m行n列的矩陣(矩陣如題目描述所示,每一行都按照從左至右遞增的順序排序,每一列都按照從上到下遞增的順序排序。

輸出:

對應每個測試案例,

輸出”Yes”代表在二維數組中找到了數字t。

輸出”No”代表在二維數組中沒有找到數字t。

範例輸入:
3 351 2 34 5 67 8 93 312 3 45 6 78 9 103 3122 3 45 6 78 9 10
範例輸出:
YesNoNo
poj地址:
http://ac.jobdu.com/problem.php?pid=1384
可以AC的代碼:
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <fstream>
#include<memory.h>
using namespace std;
 
int main()
{
    int n,m,target;
    //ifstream cin("input.txt");
    //while(cin>>m)
    while (scanf("%d%d",&m, &n) != EOF)
    {
        //cin>>n;
        bool found=false;
        int *data=new int[n*m];
        //cin>>target;
        scanf("%d",&target);
        int row,col;
        for (row=0;row<m;row++){
            for (col=0; col<n; col++) {
                //cin>>data[row*n+col];
                scanf("%d",&data[row*n+col]);
            }
        }
        row=0; col=n-1;
        while (row<m && col>=0) {
            if (data[row*n+col]==target) {
                found=true;
                break;
            }else if(data[row*n+col]<target){
                row++;
            }else{
                col--;
            }
        }
        if (found) {
            printf("Yes\n");
        }else{
            printf("No\n");
        }
        delete []data;
    }
    //getchar();
    return 0;
}
 
 
 
/**************************************************************
    Problem: 1384
    User: ycxmartin111111
    Language: C++
    Result: Accepted
    Time:680 ms
    Memory:5428 kb
****************************************************************/



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.