How to efficiently remove duplicates from an array without using Set

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

    Not a big fun of updating user input, however considering your constraints...

    public int[] removeDup(int[] nums) {
      Arrays.sort(nums);
      int x = 0;
      for (int i = 0; i < nums.length; i++) {
        if (i == 0 || nums[i] != nums[i - 1]) {
        nums[x++] = nums[i];
        }
      }
      return Arrays.copyOf(nums, x);
    }
    

    Array sort can be easily replaced with any nlog(n) algorithm.

提交回复
热议问题