在一個長度爲 n 的數組裏的全部數字都在 0 到 n-1 的範圍內。數組中某些數字是重複的,但不知道有幾個數字是重複的,也不知道每一個數字重複幾回。請找出數組中任意一個重複的數字。編程
Input: {2, 3, 1, 0, 2, 5} Output: 2
時間複雜度 O(N),空間複雜度 O(1)數組
對於範圍0到n-1的數組,最好方法是將數字0放到位置0,數字1放到位置1,以此類推. 若當前遍歷到的數字若與以前遍歷過的數重複,即爲重複數;spa
例如上面的例子,當遍歷到第5個數nums[4]=2時,數組內順序爲:[0,1,2,3,2,5],此時,nums[4]==nums[2],即nums[4]爲重複數code
public boolean duplicate(int[] nums, int length, int[] duplication) { if (nums == null || length <= 0) return false; for (int i = 0; i < length; i++) { while (nums[i] != i) { if (nums[i] == nums[nums[i]]) { duplication[0] = nums[i]; return true; } swap(nums, i, nums[i]); } } return false; } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; }