How to efficiently remove duplicates from an array without using Set

后端 未结 30 2414
情深已故
情深已故 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:53

    For a sorted Array, just check the next index:

    //sorted data!
    public static int[] distinct(int[] arr) {
        int[] temp = new int[arr.length];
    
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            int current = arr[i];
    
            if(count > 0 )
                if(temp[count - 1] == current)
                    continue;
    
            temp[count] = current;
            count++;
        }
    
        int[] whitelist = new int[count];
        System.arraycopy(temp, 0, whitelist, 0, count);
    
        return whitelist;
    }
    

提交回复
热议问题