题目链接
题目描述
解题思路
方法一:空间换时间
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> result = new ArrayList<>();
int len = nums.length;
int[] temp = new int[len+1];
for(int i=0; i<len; i++) {
if(++temp[nums[i]] == 2) {
result.add(nums[i]);
}
}
return result;
}
}
方法二:正负号做标记
由于给定的 n 个数都在 [1,n] 的范围内,如果有数字出现了两次,就意味着 [1,n] 中有数字没有出现过;
因此,我们可以尝试将每一个数放在对应的位置。由于数组的下标范围是[0,n−1],我们需要将数 i 放在数组中下标为 i−1 的位置:
- 如果 i恰好出现了一次,那么将 i 放在数组中下标为 i-1 的位置即可;
- 如果 i 出现了两次,那么我们希望其中的一个 i 放在数组下标中为 i-1 的位置,另一个 i 放置在任意「不冲突」的位置 j。也就是说,数 j+1 没有在数组中出现过。
我们也可以给 nums[i] 加上「负号」表示数 i+1 已经出现过一次。具体地,我们首先对数组进行一次遍历。当遍历到位置 i 时,我们考虑 nums[nums[i]−1] 的正负性:
- 如果 nums[nums[i]−1] 是正数,说明 nums[i] 还没有出现过,我们将 nums[nums[i]−1] 加上负号;
- 如果 nums[nums[i]−1] 是负数,说明 nums[i] 已经出现过一次,我们将 nums[i] 放入答案
class Solution {
public List<Integer> findDuplicates(int[] nums) {
int n = nums.length;
List<Integer> ans = new ArrayList<Integer>();
for (int i = 0; i < n; ++i) {
int x = Math.abs(nums[i]);
if (nums[x - 1] > 0) {
nums[x - 1] = -nums[x - 1];
} else {
ans.add(x);
}
}
return ans;
}
}