[LeetCode]Find All Duplicates in an Array

来源:互联网 发布:淘宝店铺改名生效 编辑:程序博客网 时间:2024/05/21 12:50

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;    }}
0 0
原创粉丝点击