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]
关键是,不能用extra space,不能超过O(n)时间复杂度;
因为已知a[i]是属于[1,n]的,所以a中的元素都可以在index上找到相同值,利用这点,我们在遇到一个值k的时候,可以将a[k-1]
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums.length <= 1) return res;
for (int i = 0; i < nums.length; i++) {
int next = Math.abs(nums[i]) - 1;
if (nums[next] < 0) res.add(next+1);
else nums[next] = -nums[next];
}
return res;
}
}