Leetcode - 422 Find All Duplicates in an Array (Medium)
题目描述:数组中元素的范围为 [1, n],有些元素出现两次有些出现一次,找出重复出现的元素。
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
解题思路:将访问过的元素对应位置的值设为负数,代表已经访问过,下次再访问就意味着该元素已经重复了。
public List
<Integer> findDuplicates(int[] nums
) {
List
<Integer> res
= new ArrayList<>();
for (int i
= 0; i
< nums
.length
; i
++) {
int index
= Math
.abs(nums
[i
]) - 1;
if (nums
[index
] < 0) {
res
.add(index
+ 1);
}
nums
[index
] = -nums
[index
];
}
return res
;
}