How to efficiently remove duplicates from an array without using Set

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

    Slight modification to the original code itself, by removing the innermost for loop.

    public static int[] removeDuplicates(int[] arr){
        int end = arr.length;
    
        for (int i = 0; i < end; i++) {
            for (int j = i + 1; j < end; j++) {
                if (arr[i] == arr[j]) {                  
                    /*int shiftLeft = j;
                    for (int k = j+1; k < end; k++, shiftLeft++) {
                        arr[shiftLeft] = arr[k];
                    }*/
                    arr[j] = arr[end-1];
                    end--;
                    j--;
                }
            }
        }
    
        int[] whitelist = new int[end];
        /*for(int i = 0; i < end; i++){
            whitelist[i] = arr[i];
        }*/
        System.arraycopy(arr, 0, whitelist, 0, end);
        return whitelist;
    }
    

提交回复
热议问题