[LeetCode]Find All Duplicates in an Array

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


Question

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]

本题难度Medium。

【复杂度】
时间 O(N) 空间 O(1)

【思路】
与​​[LeetCode]Find All Numbers Disappeared in an Array​​几乎一样,不同之处就是找出twice的数。那么我们只要当​​nums[i]!=i+1​​​时,然后又当​​nums[nums[i]-1]==nums[i]​​​时,把​​nums[i]​​放入set即可。

【代码】

public class Solution {
public List<Integer> findDuplicates(int[] nums) {
//require
int size=nums.length;
Set<Integer> set=new HashSet<Integer>();
//invariant
int i=0;
while(i<size){
if(nums[i]!=i+1){
if(nums[nums[i]-1]==nums[i]){
set.add(nums[i]);
i++;
}else
swap(i,nums[i]-1,nums);
}else
i++;
}
//ensure
return new LinkedList<Integer>(set);
}
private void swap(int a,int b,int[] nums){
int tmp=nums[a];
nums[a]=nums[b];
nums[b]=tmp;
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6