[Leetcode 27]Remove Element

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
int removeElement(int* nums, int numsSize, int val){
int length = 0;
int duplicate = 0; // the accumulate left shift
for(int i=0; i<numsSize; i++){ //iterate numsSize-1 times
if(nums[i] == val){
duplicate++;
}else{
nums[i-duplicate] = nums[i];
length++;
}
}
return length;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store