Leetcode学习笔记:#442. Find All Duplicates in an Array
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?
实现:
public List<Integer> findDuplicate(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(Math.abs(index+1);
nums[index] = -nums[index];
}
return res;
}
思路:
每遍历一个数字i, 将位置i-1变为负数,如果位置i-1的数字已经是负数,则说明该数字出现过两次。