80 Remove Duplicates from Sorted Array II

本文介绍了一种算法解决方案,用于将有序数组中的重复元素限制出现次数最多为两次,并返回处理后数组的有效长度。通过计数器跟踪每个数字的出现次数,并调整数组元素的位置来实现目标。

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

题目:

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.

解题思路:
这题比较简单,维护一个对相同数字的计数值,当计数值大于 2 时,就跳过该元素。
同时,还要维护一个存放当前元素的下标位置,由于前面的元素可能存在计数值大于 2 的情况,遂要把后面的元素往前挪。
特别指出,题目只关心挪动元素后新数组的前 length 个元素

代码实现:

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int n = 1;
        int tempN = 1;
        int index = 0;
        for(int i = 1; i < nums.length; i ++) {
            if(nums[i] != nums[i - 1]) {
                n ++;
                tempN = 1;
                nums[++ index] = nums[i];
            } else {
                if(tempN < 2) {
                    n ++;
                    nums[++ index] = nums[i];
                }
                tempN ++;
            }
        }
        return n;
    }
}
164 / 164 test cases passed.
Status: Accepted
Runtime: 2 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值