面試題03.數組中重複的數字
題目描述
找出數組中重複的數字。
在一個長度爲 n 的數組 nums 裏的所有數字都在 0~n-1 的範圍內。數組中某些數字是重複的,但不知道有幾個數字重複了,也不知道每個數字重複了幾次。請找出數組中任意一個重複的數字。
示例 1:
輸入:
[2, 3, 1, 0, 2, 5, 3]
輸出:2 或 3
限制:
2 <= n <= 100000
題解1
創建一個新的數組,遍歷原數組,將得到的值作爲新數組的下標,每遍歷一個新的數,對應新的數組中,下標爲該數的值加一,返回新數組中大於1的數的下標即可
class Solution {
public int findRepeatNumber(int[] nums) {
int[] arr = new int[nums.length];
for(int x=0;x<nums.length;x++){
arr[nums[x]]++;
if(arr[nums[x]]>1)
return nums[x];
}
return -1;
}
}
提交結果
題解2
先對數組進行排序,之後按順序遍歷數組,遇到相同的值返回即可,代碼如下:
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for(int x = 0;x<nums.length-1;x++){
if(nums[x]==nums[x+1])
return nums[x];
}
return -1;
}
}
提交結果
題解3
使用 HashSet 來進行處理,因爲 HashSet 本身不允許出現重複元素,所以當添加元素失敗或已經包含該數字時,則表示出現了重複元素,將其返回即可,代碼如下:
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num: nums) {
if(!set.add(num)) {
return num;
}
}
return -1;
}
}