Given an array and a value, 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 nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2.
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val) { 4 5 int cnt = 0; 6 int n = nums.size(); 7 8 for(int i = 0; i < n; ++i) 9 { 10 if(nums[i] == val) 11 { 12 ++cnt; 13 } 14 else 15 { 16 nums[i-cnt] = nums[i]; 17 } 18 19 20 } 21 22 return n - cnt; 23 } 24 };