# 【LeetCode】 26. Remove Duplicates from Sorted Array ## Description > Given a sorted array nums, remove the duplicates in-place such that each element appear only once 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. > 給一個已經排序完的陣列nums,用in-place演算法移除重複的元素,使每個元素都只會出現一次,並回傳新的長度。 > 不要去分配額外的空間給其他陣列,你應該直接修改輸入的陣列,空間複雜度應為O(1)。 ## Example: ``` Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length. ``` ## Solution * 紀錄第一個元素在`temp`。 * 遍歷陣列,如果和`temp`一樣,就移除;否則將`temp`更新。 * 其他注意:用`nums.size()`的速度很慢,你可以另外用一個空間去儲存、操作它。 * 其他注意:用這個Code跑LeetCode的速度會輸給超多人,原因是其他人沒有使用in-place演算法,但評測程式不會抓。 ### Code ```C++=1 class Solution { public: int removeDuplicates(vector<int>& nums) { int s = nums.size(); if(s==0)return 0; int temp = nums[0]; for(int i =1;i<s;) { if(temp == nums[i]) { s--; nums.erase(nums.begin() + i); } else { temp = nums[i]; i++; } } return s; } }; ``` ###### tags: `LeetCode` `C++`