• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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, 重复的在最后一个数。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#实现在注册表中保存信息发布时间:2022-07-10
下一篇:
C#对XML文件的操作发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap