Find Duplicate 系列
经典题目
1 <= a[i] <= n, a.length == n + 1, find the duplicate one.
// T/O(n), S/O(1)
1 <= a[i] <= n, a.length == n, some appear twice and others appear once.
// T/O(n), S/O(1)
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] > 0) {
nums[index] = -nums[index];
} else {
ans.add(index + 1);
}
}
return ans;
}Last updated