题目描述:
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:2 <= n <= 100000
我的解题思路:哈希表,存储遍历过的数字,遇到重复存储过的数字即返回
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num)) {
return num;
} else {
set.add(num);
}
}
return -1;
}
复杂度分析:
时间复杂度 O(N): 遍历数组使用 O(N) ,HashSet 添加与查找元素皆为 O(1) 。
空间复杂度 O(N): HashSet 占用O(N) 大小的额外空间。
参考解题思路二:原地交换,因题目可知,数字大小在 0~n-1范围内,所以数组长度必定有重复数字,每个数字一个坑,将数字交换到对应数组下标位置存放,如遇到该交换的两个数值相等则返回。
public int findRepeatNumber(int[] nums) {
int index = 0;
while (index <= nums.length - 1) {
// 下标元素等于下标对应值
if (nums[index] == index) {
index++;
continue;
}
// 找到重复元素
if (nums[index] == nums[nums[index]]) {
return nums[index];
}
// 原地交换数组值
int temp = nums[index];
nums[index] = nums[temp];
nums[temp] = temp;
}
return -1;
}
复杂度分析:
时间复杂度 O(N) : 遍历数组使用 O(N) ,每轮遍历的判断和交换操作使用 O(1) 。
空间复杂度 O(1): 使用常数复杂度的额外空间。