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.
給定一個排序過的陣列,移除重複的元素,回傳新的陣列長度,
不能建立新的陣列,空間複雜度為O(1)
Input: [1,1,2]
Output: 2
Input: [0,0,1,1,1,2,2,3,3,4]
Output: 5
第i
個元素與第i+1
個元素若相等的話,移除第i+1
個元素,再將i
倒退。
var removeDuplicates = function(nums) {
let i = 0;
for (i; i < nums.length; i++) {
if (nums[i] === nums[i + 1]) {
nums.splice(i + 1, 1);
i--;
}
}
return i;
};