題目描述:
找出數組中重複的數字。
在一個長度爲 n 的數組 nums 裏的所有數字都在 0~n-1 的範圍內。數組中某些數字是重複的,但不知道有幾個數字重複了,也不知道每個數字重複了幾次。請找出數組中任意一個重複的數字。
示例 1:
輸入:
[2, 3, 1, 0, 2, 5, 3]
輸出:2 或 3
限制:
2 <= n <= 100000
思路:模擬一個哈希思想的動態數組,遇到重複的即退出。或者藉助容器Set元素唯一性的特點
1. 排序
若相鄰兩個元素相等,則返回
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i-1])
return nums[i];
}
return -1;
}
}
//時間複雜度高
2. 哈希表(數組)
- 由於數組元素的值都在指定的範圍內,這個範圍恰恰好與數組的下標可以一一對應
- 因此看到數值,就可以知道它應該放在什麼位置,這裏數字nums[i] 應該放在下標爲 i 的位置上,這就像是我們人爲編寫了哈希函數,這個哈希函數的規則還特別簡單
- 而找到重複的數就是發生了哈希衝突
public int findRepeatNumber(int[] nums) {
int[] count = new int[nums.length];
for(int i : nums){
if(count[i] == 1)
return i;
count[i] = 1;
}
return -1;
}
3. 哈希表(Set容器)
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int temp = -1;
for (int num : nums) {
if (!set.add(num)) {
temp = num;
break;
}
}
return temp;
}
}
4. 原地置換(排序)
如果沒有重複數字,那麼正常排序後,數字i應該在下標爲i的位置,所以思路是重頭掃描數組,遇到下標爲i的數字如果不是i的話,(假設爲j),那麼我們就拿與下標j的數字交換。在交換過程中,如果有重複的數字發生,那麼終止返回該數字
class Solution {
public int findRepeatNumber(int[] nums) {
int temp = 0;
for(int i=0; i < nums.length; i++){
while (nums[i] != i){
if(nums[i] == nums[nums[i]]){
return nums[i];
}
temp = nums[i];
nums[i] = nums[temp];
nums[temp] = temp;
}
}
return -1;
}
}