Problem Description:
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
Analysis:
方法一:本题使用Set的数据结构对数组进行遍历,找到出现两次的元素。
方法二:第一次遍历数组,将没有访问的元素其值求反;第二次再次访问如果其值为负则其被反问过两次。
代码如下:
Code:
方法一:
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
Set<Integer> temp = new HashSet<>();
for(int i = 0; i < nums.length; i++) {
if(temp.contains(nums[i])) {
res.add(nums[i]);
} else {
temp. add(nums[i]);
}
}
return res;
}
}
方法二:
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
if(nums[i] > 0) {
if(nums[nums[i] - 1] > 0) {
nums[nums[i] - 1] *= -1;
} else {
res.add(nums[i]);
}
} else {
if(nums[Math.abs(nums[i]) - 1] > 0) {
nums[Math.abs(nums[i]) - 1] *= -1;
} else {
res.add(Math.abs(nums[i]));
}
}
}
return res;
}
}