【leetcode】已排序数组去重 II

本文解决LeetCode上的经典问题——删除排序数组中的重复项,使其每个元素最多出现两次,并返回新长度。文章提供了一种有效的解决方案,利用原地操作实现目标,无需额外分配空间。

80. Remove Duplicates from Sorted Array II

leetcode题目描述

题目描述:

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
················································································································································
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.

题解:

给定一个排序的数组,删除重复,使每个元素最多允许重复两次,并返回新的长度。
不开另外的数组,使得原数组前几位(new length)即为去重后结果。

已知若原数组长度大于2,初始length=2,且已经确定0,1位置值一定正确。
设length-2位置的值为参考值flag,
只需从未定部分找到第一个与flag值不同的元素,即为nums[length]的值。
这里写图片描述

solution1:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() <= 2) {
            return nums.size();
        }
        int length = 2;
        /* 允许重复最多两次 */ 
        /* 从length-2(=0)位置开始,比较与i(=2)位置的值是否相等:
        不等:此位置值正确,length++, i++(同时更新)
        相等:此位置值多余,不增加长度,仅i++,
        */ 
        for (int i = 2; i < nums.size(); i++) {
            int flag = nums[length-2];
            if (flag != nums[i] ) {
                nums[length] = nums[i];
                length++;
            }
        }
        return length;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值