原题:
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?
示例:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
思路:此题类似于448题。求的是出现过两次的数字。采用+n的方式来标记出现次数,出现一次的加一个n.出现两次的加两个n。n为数组的长度。
public class Solution442 {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> list = new ArrayList<>();
int n=nums.length;
for (int i = 0; i < n; i++) {
int temp = (nums[i] - 1) % n;
nums[temp] += n;
}
for (int i=0;i<n;i++){
if (((nums[i]-1)/n)==2){
list.add(i+1);
}
}
return list;
}