Monday, June 24, 2019

Remove Given Element in array and return new length

Given an array nums and a value val, 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.
Example:
Given list = [1, 5, 3, 2, 3], val = 2
Output should be - length = 4
Another Example:
Given list = [1, 4, 1, 12, 3, 1, 0, 3], val = 1
length = 5, list = [4, 12, 3, 0, 3] 

Solution:
public int removeElement(int[] list, int val) {
    int i = 0;
    for (int j = 0; j < list.length; j++) {
        if (list[j] != val) {
            list[i] = list[j];
            i++;
        }
    }
    return i;
}