LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II

本文介绍了一个算法问题的解决方案:如何在一个已排序的数组中移除多余的重复元素,使得每个元素最多只出现两次。通过具体示例和代码实现,展示了如何有效地完成这一任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].

 1         public static int RemoveDuplicatesfromSortedArrayII(int[] A)
 2         {
 3             int prev = A[0];
 4             int numtoremove = 0;
 5             int ret = A.Length;
 6 
 7             for (int i = 1; i < ret; i++)
 8             {
 9                 if (prev == A[i])
10                 {
11                     numtoremove++;
12                 }
13                 else
14                 {
15                     if (numtoremove > 1)
16                     {
17                         RemoveDuplicatesfromSortedArrayShiftLeft(A, ret, i, numtoremove - 1);
18                         ret -= numtoremove - 1;
19                         i -= numtoremove - 1;
20                     }
21                     prev = A[i];
22                     numtoremove = 0;
23                 }
24             }
25 
26             if (numtoremove > 1)
27             {
28                 ret -= numtoremove - 1;
29             }
30 
31             return ret;
32         }
33         
34         public static void RemoveDuplicatesfromSortedArrayShiftLeft(int[] A, int alength, int index, int n)
35         {
36             for (int i = index; i < alength; i++)
37             {
38                 A[i - n] = A[i];
39             }
40         }

代码分析:

  也不难,少remove一个而已,但是要记得 prev = A[i], numtoremove = 0 在下一个不重复处就都需要做。 同样不能忘了最后一个数重复的corner case。

转载于:https://www.cnblogs.com/etcow/archive/2012/10/11/2720663.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值