26. Remove Duplicates from Sorted Array

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開始,判斷當前位與下一位是否相同,如果相同,則把當前位之后的元素都往前移一位 (一個外部循環+一個if+一個前移循環)
// 還要再判斷往前移了以后的當前位是否還是和下一位相同 (一個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類型轉換再變成數組,簡單粗暴

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容