minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

20 -【leetcode】删除有序数组中的重复项 #20

Open wucuiping opened 3 years ago

wucuiping commented 3 years ago

leetcode-删除有序数组中的重复项

minjs1cn commented 3 years ago

数组左移一位

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    const map = new Map()
    for(let i = 0; i < nums.length; i ++) {
        if (map.has(nums[i])) {
            for(let j = i; j < nums.length - 1; j ++) {
                nums[j] = nums[j+1]
            }
            nums.length -= 1
            i -= 1
        } else {
            map.set(nums[i], i)
        }
    }
    return nums.length
};
wucuiping commented 3 years ago
/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    let a = 0
    if (nums.length === 0) {
        return 0
    }
    while((a + 1) < nums.length) {
        if (nums[a] === nums[a+1]) {
            nums.splice(a+1,1)
        } else {
            ++a
        }
    }
    return nums.length
};