算法题目
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]