找出數組中重複的數字。
在一個長度為 n 的數組 nums 裡的所有數字都在 0~n-1 的範圍內。數組中某些數字是重複的,但不知道有幾個數字重複了,也不知道每個數字重複了幾次。請找出數組中任意一個重複的數字。
示例 1:
<code>輸入:
[2, 3, 1, 0, 2, 5, 3]
輸出:2 或 3
/<code>
限制:
2 <= n <= 100000
算法1:利用數組
<code>class Solution {
public int findRepeatNumber(int[] nums) {
int[] arr = new int[nums.length];
for(int i=0; i<nums.length> arr[nums[i]]++;
if(arr[nums[i]]>1) return nums[i];
}
return -1;
}
}/<nums.length>/<code>
算法2:利用HashSet
<code>class Solution {
public int findRepeatNumber(int[] nums) {
Set<integer> set = new HashSet<integer>();
int repeat = -1;
for (int num : nums) {
if (!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
}/<integer>/<integer>/<code>
閱讀更多 新視像 的文章