How to efficiently remove duplicates from an array without using Set

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

    Note: I am assuming the array is sorted.

    Code:

    int[] input = new int[]{1, 1, 3, 7, 7, 8, 9, 9, 9, 10};
    int current = input[0];
    boolean found = false;
    
    for (int i = 0; i < input.length; i++) {
        if (current == input[i] && !found) {
            found = true;
        } else if (current != input[i]) {
            System.out.print(" " + current);
            current = input[i];
            found = false;
        }
    }
    System.out.print(" " + current);
    

    output:

      1 3 7 8 9 10
    

提交回复
热议问题