前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >① Remove Duplicates from Sorted Array

① Remove Duplicates from Sorted Array

作者头像
大牧莫邪
发布2022-03-23 14:20:25
2360
发布2022-03-23 14:20:25
举报

算法题目

Given a sorted array, 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 in place with constant memory. For example, Given input array A = [1,1,2], Your function should return length = 2, and A is now [1,2].

给定一个已排序的数组,在适当的位置删除重复项,使每个元素只出现一次,并返回新的长度。 不要为另一个数组分配额外的空间,必须在内存不变的情况下就地分配。

解决方案:

因为是已经排序的数组,通过两个变量遍历整个数组,第一个变量slow从0开始用于存储非重复的数据,第二个变量fast从1开始编辑剩余所有数据,遍历过程中将所有不重复的数据依次记录到++slow中,最终形成了剔除重复元素的数据并完成了数据量slow+1记录!

算法原理

20160916210024639.gif

JavaScript代码实现:

代码语言:javascript
复制
function removeDuplicates(arr) {
    if(arr.length <= 0){
        return 0
    }
    let slow = 0
    for(let fast = 1; fast < arr.length; fast ++) {
        if(arr[slow] != arr[fast]) {  // 1, 1, 2
            arr[++slow] = arr[fast]
        }
    }
    return slow + 1
}

let a = [1, 1, 2];
console.log(removeDuplicates(a), a) // 2, [1, 2, 2]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022.03.08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档