# 【LeetCode】 27. Remove Element ## 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. > 給一陣列和一數字val,請移除陣列中所有和val相等的元素,並回傳新的長度。 > 請不要分配額外的空間給一個新的陣列,你應該直接修改輸入提供的陣列。你只能用O(1)的空間。 > 陣列的元素可以改變,你移除了什麼並不影響回傳的長度。 ## Example: ``` Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. *It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. *It doesn't matter what values are set beyond the returned length. ``` ## Solution * 掃過一次陣列,相同就移除,複雜度為`O(n)`。 * 注意`vector.size`的提取對時間的影響,你可以先把它放到一個空間裡儲存。 ### Code ```C++=1 class Solution { public: int removeElement(vector<int>& nums, int val) { int s = nums.size(); for(int i = 0;i<s;) { if(nums[i]==val) { nums.erase(nums.begin()+i); s--; } else i++; } return s; } }; ``` ###### tags: `LeetCode` `C++`