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类型转换再变成数组,简单粗暴

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容