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

本文介绍了一种在不使用额外空间的情况下从有序数组中去除重复元素的方法,并提供了一个具体的C#实现示例。该算法通过移动数组元素来达到去除重复的目的。

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].

 1         public static int RemoveDuplicatesfromSortedArray(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 > 0)
16                         RemoveDuplicatesfromSortedArrayShiftLeft(A, ret, i, numtoremove);
17                     ret -= numtoremove;
18                     i -= numtoremove;
19                     numtoremove = 0;
20                     prev = A[i];
21                 }
22             }
23 
24             if (numtoremove > 0)
25             {
26                 ret -= numtoremove;
27             }
28 
29             return ret;
30         }
31 
32         public static void RemoveDuplicatesfromSortedArrayShiftLeft(int[] A, int alength, int index, int n)
33         {
34             for (int i = index; i < alength; i++)
35             {
36                 A[i - n] = A[i];
37             }
38         }

代码分析:

  不难,用numtoremove存着几个重复的,然后remove掉(拷贝后面的上来)就可以了。

  注意容易出错的是,ret(数组长度)要记得改,i 要记得改, prev 要记得改, numtoremove 要记得清零。

  还有记得处理corner case, 重复的在最后一个数。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值