How to efficiently remove duplicates from an array without using Set

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

    Why do all people not check this below lines?

    I need to write my own implementation - not to use Set, HashSet etc. Or any other tools such as iterators. Simply an array to remove duplicates.

    I'm posting very simple implementation with caring the above line.

    public class RemoveDuplicates {
    
    public static void main(String[] args) {
    
        int[] arr = { 1, 2, 3, 4, 2, 3, 1 }; // input array
        int len = arr.length;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < len; j++) {
                if (arr[i] == arr[j]) {
                    while (j < (len) - 1) {
                        arr[j] = arr[j - 1];
                        j++;
                    }
                    len--;
                }
            }
        }
        for (int i = 0; i < len; i++) {
            System.out.print("  " +arr[i]);
        }
    
       }
     }
    

    Input : 1, 2, 3, 4, 2, 3, 1

    Output : 1 2 3 4

提交回复
热议问题