程式員面試題精選(10):在排序數組中尋找和為給定值的兩個數字

來源:互聯網
上載者:User

題目:輸入一個已經按升序排序過的數組和一個數字,在數組中尋找兩個數,使得它們的和正好是輸入的那個數字。要求時間複雜度是O(n)。如果有多對數位和等於輸入的數字,輸出任意一對即可。

例如輸入數組1、2、4、7、11、15和數字15。由於4+11=15,因此輸出4和11。

分析:如果我們不考慮時間複雜度,最簡單想法的莫過去先在數組中固定一個數字,再依次判斷數組中剩下的n-1個數字與它的和是不是等於輸入的數字。可惜這種思路需要的時間複雜度是O(n2)。

我們假設現在隨便在數組中找到兩個數。如果它們的和等於輸入的數字,那太好了,我們找到了要找的兩個數字;如果小於輸入的數字呢?我們希望兩個數位和再大一點。由於數組已經排好序了,我們是不是可以把較小的數位往後面移動一個數字?因為排在後面的數字要大一些,那麼兩個數位和也要大一些,就有可能等於輸入的數字了;同樣,當兩個數位和大於輸入的數位時候,我們把較大的數字往前移動,因為排在數組前面的數字要小一些,它們的和就有可能等於輸入的數字了。

我們把前面的思路整理一下:最初我們找到數組的第一個數字和最後一個數字。當兩個數位和大於輸入的數字時,把較大的數字往前移動;當兩個數位和小於數字時,把較小的數字往後移動;當相等時,打完收工。這樣掃描的順序是從數組的兩端向數組的中間掃描。

問題是這樣的思路是不是正確的呢?這需要嚴格的數學證明。感興趣的讀者可以自行證明一下。

參考代碼:

///////////////////////////////////////////////////////////////////////
// Find two numbers with a sum in a sorted array
// Output: ture is found such two numbers, otherwise false
///////////////////////////////////////////////////////////////////////
bool FindTwoNumbersWithSum
(
      int data[],           // a sorted array
      unsigned int length,  // the length of the sorted array     
      int sum,              // the sum
      int& num1,            // the first number, output
      int& num2             // the second number, output
)
{

      bool found = false;
      if(length < 1)
            return found;

      int ahead = length - 1;
      int behind = 0;

      while(ahead > behind)
      {
            long long curSum = data[ahead] + data[behind];

            // if the sum of two numbers is equal to the input
            // we have found them
            if(curSum == sum)
            {
                  num1 = data[behind];
                  num2 = data[ahead];
                  found = true;
                  break;
            }
            // if the sum of two numbers is greater than the input
            // decrease the greater number
            else if(curSum > sum)
                  ahead --;
            // if the sum of two numbers is less than the input
            // increase the less number
            else
                  behind ++;
      }

      return found;
}

擴充:如果輸入的數組是沒有排序的,但知道裡面數位範圍,其他條件不變,如和在O(n)時間裡找到這兩個數字?

 

聯繫我們

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