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]
与289. Game of Life一题中的思路类似,让a[i]有两层含义;第一层含义:数a[i]出现过一次;第二层含义:a[i]的正负(由题意可知:1 ≤ a[i] ≤ n且数a[i]只可能出现一次或者两次)表示数(i+1)已经出现过的次数,为正数表示出现过0次,为负数表示出现过1次。
具体代码思路如下:
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
int index;
for(int i = 0; i < nums.length; ++i) {
index = Math.abs(nums[i]) - 1;
if(nums[index] < 0)//或数(index+1)再次出现,则概述已出现两次(一个数只会出现一次或两次,所以不会重复添加)
ans.add(index + 1);
nums[index] = -nums[index];//表示数(index+1)已经出现一次
}
return ans;
}