How to efficiently remove duplicates from an array without using Set

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

    I know this is kinda dead but I just wrote this for my own use. It's more or less the same as adding to a hashset and then pulling all the elements out of it. It should run in O(nlogn) worst case.

        public static int[] removeDuplicates(int[] numbers) {
        Entry[] entries = new Entry[numbers.length];
        int size = 0;
        for (int i = 0 ; i < numbers.length ; i++) {
            int nextVal = numbers[i];
            int index = nextVal % entries.length;
            Entry e = entries[index];
            if (e == null) {
                entries[index] = new Entry(nextVal);
                size++;
            } else {
                if(e.insert(nextVal)) {
                    size++;
                }
            }
        }
        int[] result = new int[size];
        int index = 0;
        for (int i = 0 ; i < entries.length ; i++) {
            Entry current = entries[i];
            while (current != null) {
                result[i++] = current.value;
                current = current.next;
            }
        }
        return result;
    }
    
    public static class Entry {
        int value;
        Entry next;
    
        Entry(int value) {
            this.value = value;
        }
    
        public boolean insert(int newVal) {
            Entry current = this;
            Entry prev = null;
            while (current != null) {
                if (current.value == newVal) {
                    return false;
                } else if(current.next != null) {
                    prev = current;
                    current = next;
                }
            }
            prev.next = new Entry(value);
            return true;
        }
    }
    

提交回复
热议问题