Remove Element

Problem:

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Subscribe to see which companies asked this question
Leetcode link
Lintcode link

Solution:

Use a ponter to point to the end index of the array. Go through the array, if the current element equals to the target value, swap the current value with the value at the end index, and then move the end pointer a unit towards the start direction. Then repeat.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*************************************************************************
> File Name: RemoveElement.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Thu 12 Nov 12:15:44 2015
************************************************************************/


public class RemoveElement{
public int removeElement(int[] nums, int val) {
int endIndex = nums.length - 1;

int index = 0;
while (index <= endIndex){
if (nums[index] == val){
int temp = nums[index];
nums[index] = nums[endIndex];
nums[endIndex] = temp;
endIndex--;
} else {
index++;
}
}

return endIndex + 1;
}
}