② Remove Duplicates from Sorted Array 2

2022-03-23 14:20:39 浏览数 (4)

算法题目

Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]

解决方案:

通过变量index记录每个元素出现的次数 因为是已经排序的数组,所以直接进行相邻元素的总数记录即可!

JavaScript代码实现:

代码语言:javascript复制
/*
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
*/
function removeDuplicates(arr) {
    if(arr.length <= 2) {
        return arr.length
    }

    let index = 2
    for(let i = 2; i < arr.length; i  ) {
        if(arr[i] != arr[index-2]) {
            arr[index  ]=arr[i]
        }
    }
    return index
}

const arrs = [1,1,1,2,2,3,4,4,4]             //                  v
console.log(removeDuplicates(arrs), arrs)   // 7, [1,1,2,2,3,4,4 ,4,4]

1 人点赞