劍指offer系列源碼-和為S的兩個數字

來源:互聯網
上載者:User

標籤:blog   io   os   sp   for   2014   log   amp   as   

題目1352:和為S的兩個數字時間限制:2 秒記憶體限制:32 兆特殊判題:否提交:2651解決:668題目描述:輸入一個遞增排序的數組和一個數字S,在數組中尋找兩個數,是的他們的和正好是S,如果有多對數位和等於S,輸出兩個數的乘積最小的。輸入:每個測試案例包括兩行:第一行包含一個整數n和k,n表示數組中的元素個數,k表示兩數之和。其中1 <= n <= 10^6,k為int第二行包含n個整數,每個數組均為int類型。輸出:對應每個測試案例,輸出兩個數,小的先輸出。如果找不到,則輸出“-1 -1”範例輸入:6 151 2 4 7 11 15範例輸出:4 11

#include <iostream>#include<stdio.h>using namespace std;int main(){    int n,sum;    while(scanf("%d%d",&n,&sum)!=EOF){        int* data = new int[n];        for(int i=0;i<n;i++){            scanf("%d",&data[i]);        }        int* begin = data;        int* end = data+n-1;        bool found = false;        while(begin<end){            int s = *begin+*end;            if(s==sum){                found = true;                break;            }else if(s<sum){                begin++;            }else{                end--;            }        }        if(found){            printf("%d %d\n",*begin,*end);        }else{            printf("-1 -1\n");        }    }    return 0;}

劍指offer系列源碼-和為S的兩個數字

聯繫我們

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