美文网首页leetcode --- js版本程序员
leetcode-Easy-第7期-数组类型-Remove Du

leetcode-Easy-第7期-数组类型-Remove Du

作者: 石头说钱 | 来源:发表于2019-03-05 11:01 被阅读14次

题目:

  • 在不额外创建数组的情况下,通过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
}

相关文章

网友评论

    本文标题:leetcode-Easy-第7期-数组类型-Remove Du

    本文链接:https://www.haomeiwen.com/subject/duseuqtx.html