一個數組面試題

來源:互聯網
上載者:User

In an unsorted array of first N natural numbers. The array contains a number which is duplicated and one is missing. Find both the numbers. 一個含有前N個自然數的未排序數組,其中一個數出現了兩次,一個沒有出現,找出這兩個數。

來源:careercup 亞馬遜美國面試題 http://www.careercup.com/question?id=13729662

【解答】

首先很容易想到naive approach,建立一個大小為N的數組作為flag,時間複雜度為O(N),另外需要O(N)的space。

這裡CodeCracker 利用數學方法給出了一個很好的解答。

前N個自然數的和是(n+1) n / 2,設重複出現的數是x,沒出現的數是y,則輸入數組的和是(n+1)*n +x - y;同樣前N個自然數的平方和是 n*(n+1)(2n+1)/6,輸入數組的平方和是 n*(n+1)(2n+1)/6 +x^2-y^2,於是我們可以算出 ( x -  y ) 和 ( x^2 - y^2 ),進而算出x 和 y。因為需要一次求和過程,時間複雜度為O(N)。

下面給出JAVA語言的演算法實現:

package mianshiti;/** * 尋找一個數組中的重複出現的數字和沒有出現的數字 * @author majing *題目:一個含有N個自然數的未排序數組中,其中一個數出現兩次,一個數沒有出現,現在需要找出這兩個數 */public class SearchDupAndMiss {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[] array={1,2,4,6,5,6,7};search(array,array.length);}public static void search(int[] array,int length){int errorsum=0;int squareerror=0;for(int i=0;i<length;i++){errorsum+=(array[i]-(i+1));squareerror+=(array[i]*array[i]-(i+1)*(i+1));}squareerror/=errorsum;System.out.println("重複的數為:"+(squareerror+errorsum)/2);System.out.println("丟失的數為:"+(squareerror-errorsum)/2);}}

在上面的程式中,errorsum記錄原數組與正常的前N個自然數組成的數組的差值,而squareerror記錄著兩個數組的平方差值,根據上面闡述可以知道

x-y=errorsum

x^2 - y^2=squareerror

所以

x+y=squareerror/errorsum

 

重複的數為:6丟失的數為:3

 

 

聯繫我們

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