I solved this problem:
Given an array
nums
and a valueval
, remove all instances of that value in-place 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. The order of elements can be changed. It doesn't matter what you leave beyond the new length.
How can I improve its execution time and also, if there is any better way of doing it?
public int removeElement(int[] numbers, int value) {
int index = 0;
for(; index < numbers.length; index++) {
if(numbers[index] == value) {
boolean otherNumberPresent = false;
int j = index + 1;
for(; j < numbers.length; j++ ){
if(numbers[j] != value) {
otherNumberPresent = true;
break;
}
}
if(otherNumberPresent) {
int temp = numbers[j];
numbers[j] = numbers[index];
numbers[index] = temp;
} else {
return index;
}
}
}
return index;
}