How to efficiently remove duplicates from an array without using Set

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

    Since you can assume the range is between 0-1000 there is a very simple and efficient solution

    //Throws an exception if values are not in the range of 0-1000
    public static int[] removeDuplicates(int[] arr) {
        boolean[] set = new boolean[1001]; //values must default to false
        int totalItems = 0;
    
        for (int i = 0; i < arr.length; ++i) {
            if (!set[arr[i]]) {
                set[arr[i]] = true;
                totalItems++;
            }
        }
    
        int[] ret = new int[totalItems];
        int c = 0;
        for (int i = 0; i < set.length; ++i) {
            if (set[i]) {
                ret[c++] = i;
            }
        }
        return ret;
    }
    

    This runs in linear time O(n). Caveat: the returned array is sorted so if that is illegal then this answer is invalid.

提交回复
热议问题