题目:
- 在不额外创建数组的情况下,通过O(1),去掉已经排好序的数组重复元素,返回长度
Given a sorted array nums, 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.
- 解法
const removeDuplicaties = (arrs) => {
const len = arrs.length
for(let i = 0; i < len; i++ ){
if(arrs[i] !== arrs[i + 1]){
arrs.push(arrs[i])
}
}
return arrs.splice(0,len).length
}
- Es6更简单办法,但是要创建一个新的数组,不符合题意
const removeDuplicaties = (arrs) => {
const noRepeat = new Set(arrs) //没创建一个对象就要消耗内存空间
return noRepeat.length
}
网友评论