题目

分析
方法:遍历数组,存储到哈希表或数组中,判断哈希表值或数组值
代码
//时间复杂度为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;
}
}
本文介绍了一种在数组中查找重复数字的算法,通过使用哈希集或数组存储并检查元素,实现时间复杂度O(n)和空间复杂度O(n)。提供了两种实现方式,一种是使用HashSet进行元素检查,另一种是利用数组进行计数。
334





