https://leetcode.com/problems/find-all-duplicates-in-an-array/
- Index Marking
Use sign flipping or index marking: for each num, check index abs(num)-1; if already negative, it's a duplicate.
O(n)
O(1) (output excluded)
import java.util.*;
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int idx = Math.abs(nums[i]) - 1;
if (nums[idx] < 0) res.add(Math.abs(nums[i]));
else nums[idx] = -nums[idx];
}
return res;
}
}