數組中重複的數字(Java實現)__Java

來源:互聯網
上載者:User

本題為劍指offer面試題51


牛客網測試地址:https://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8


[編程題]數組中重複的數字 熱度指數:40653  時間限制:1秒  空間限制:32768K 在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那麼對應的輸出是重複的數字2或者3。

Java代碼如下:

package go.jacob.day529;//Parameters://    numbers:     an array of integers//    length:      the length of array numbers//    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;//                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++//    這裡要特別注意~返回任意重複的一個,賦值duplication[0]// Return value:       true if the input is valid, and there are some duplications in the array number//                     otherwise falsepublic class Demo1 {/* * 方法一:時間複雜度O(n),空間複雜度O(n) 運用雜湊表的原理 非最優解法 */public boolean duplicate_1(int numbers[], int length, int[] duplication) {if (numbers == null || length <= 0)return false;// 必須保證數組中的元素都在0到n-1之間for (int i = 0; i < length; i++)if (numbers[i] < 0 || numbers[i] > length)return false;int[] count = new int[length];for (int i = 0; i < length; i++) {count[i] = 0;}for (int i = 0; i < length; i++) {if (count[numbers[i]] == 1) {duplication[0] = numbers[i];return true;}count[numbers[i]]++;}return false;}/* * 方法二:時間複雜度O(n),空間複雜度O(1) 最優解法:雖然代碼中有一個二重迴圈,但每個數字最多隻要交換兩次就能找到屬於它自己的 * 位置,因此總的時間複雜度是O(n) */public boolean duplicate_2(int numbers[], int length, int[] duplication) {if (numbers == null || length <= 0)return false;for (int i = 0; i < length; i++)if (numbers[i] < 0 || numbers[i] >= length)return false;for (int i = 0; i < length; i++) {while (numbers[i] != i) {if (numbers[numbers[i]] == numbers[i]) {duplication[0] = numbers[i];return true;}// 交換int tmp = numbers[i];numbers[i] = numbers[tmp];numbers[tmp] = tmp;}}return false;}}

聯繫我們

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