② Remove Duplicates from Sorted Array 2

算法题目

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代码实现:

/*
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]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容