题目
分析
方法:遍历数组,存储到哈希表或数组中,判断哈希表值或数组值
代码
//时间复杂度为O(n),空间复杂度为O(n)
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;
}
}
//来源:力扣(LeetCode)官方
//时间复杂度为O(n),空间复杂度为O(n)
class Solution {
public int findRepeatNumber(int[] nums) {
int[] arr = new int[nums.length];
for(int i = 0; i < nums.length; i++){
arr[nums[i]]++;
if(arr[nums[i]] > 1) return nums[i];
}
return -1;
}
}