Remove duplicates from sorted array, in place 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 &lt; numbers.length - 1; index++) {
        if (numbers[index] != numbers[index+1]) {
            numbers[indexForUniqueElements++] = numbers[index];
          }
    }
    numbers[indexForUniqueElements++] = numbers[numbers.length - 1];
    return indexForUniqueElements;
  }
I don't see any way to greatly increase performance since your algorithm is already O(n).

However, there is a minor optimization that can be made.  You should try to avoid having a calculation as the limit in a for loop.  This gets calculated on each iteration of the loop.  Initialize a variable with the result and use that instead:

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