How to efficiently remove duplicates from an array without using Set

后端 未结 30 2532
情深已故
情深已故 2020-11-22 07:29

I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long ti

30条回答
  •  囚心锁ツ
    2020-11-22 07:58

    public static int[] removeDuplicates(int[] arr){
        HashSet set = new HashSet<>();
        final int len = arr.length;
        //changed end to len
        for(int i = 0; i < len; i++){
            set.add(arr[i]);
        }
    
        int[] whitelist = new int[set.size()];
        int i = 0;
        for (Iterator it = set.iterator(); it.hasNext();) {
            whitelist[i++] = it.next();
        }
        return whitelist;
    }
    

    Runs in O(N) time instead of your O(N^3) time

提交回复
热议问题