Description:
Given a sorted array, 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.
Example:
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 new length.
My code:
/**
* @param {number[]} nums
* @return {number}
*/
// 從數組下標0開始,判斷當前位與下一位是否相同栖茉,如果相同撒轮,則把當前位之后的元素都往前移一位 (一個外部循環(huán)+一個if+一個前移循環(huán))
// 還要再判斷往前移了以后的當前位是否還是和下一位相同 (一個if)
var removeDuplicates = function(nums) {
let i = 0;
while(i < nums.length - 1) {
if(nums[i] == nums[i + 1]) {
for(let j = i; j < nums.length; j++) {
nums[j] = nums[j + 1];
}
nums.pop();
}
if(nums[i] == nums[i + 1]) {
continue;
} else {
i++;
}
}
return nums.length;
};
Note: 由于題目要求使用in-place,不然可以直接把轉換為set類型轉換再變成數組,簡單粗暴