Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How can I remove duplicates from sorted array java?

Asked by Aryan Gupta Oct 11, 2022 1.1K views 1 answer
Share

About this question

I solved this problem:


Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.


How can I improve its execution time? Is there any better way of doing it?


public int removeDuplicates(int[] numbers) {
    if(numbers.length == 0 || numbers.length == 1) {
        return numbers.length;
    }
    int indexForUniqueElements = 0;
    for (int index = 0; index < numbers>        if (numbers[index] != numbers[index+1]) {
            numbers[indexForUniqueElements++] = numbers[index];
          }
    }
    numbers[indexForUniqueElements++] = numbers[numbers.length - 1];
    return indexForUniqueElements;
  }


Your answer

1 Answer

More Java discussions