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

[LeetCode] 80. Remove Duplicates from Sorted Array II

作者头像
用户1148830
发布2018-01-03 17:42:44
4390
发布2018-01-03 17:42:44
举报

【原题】 Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice?

For example, Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length. 【解释】 作为删除数组中重复元素的进化版,要求最后目标数组中最多只能有每个元素最多重复两次。 【思路】 在Remove Duplicates from Sorted Array一题中,我们只需要记录目标数组下一个该插入的位置,让后续符合要求的元素插入该位置即可。利用同样的思想,只是在比较的时候不是和前一个元素比较,而是前两个元素。

代码语言:javascript
复制
public int removeDuplicates(int[] nums) {
        int pos=0;//记录下一个插入的位置
        for(int i=0;i<nums.length;i++){
            if(i<2||nums[i]>nums[pos-2])//和前两个元素比较
                nums[pos++]=nums[i];
        }
        return pos;//犹豫pos从零开始,所以最后即为目标数组的长度
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年06月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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