LeetCode:27.Remove Element

Problem Description

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.

Analysis

Same as the Question 26, change the array and only part of them is required.
Try the same thinking as Question 26.
Use two cursors, 1(int index) is for index and 1(int i) is for going through all the elements.
If only the nums[i] does not equal to the target value, put it at the nums[index]

Right Code

1
2
3
4
5
6
7
8
9
public int removeElement(int[] nums, int val) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[index++] = nums[i];
}
}
return index;
}