Leetcode OJ: Remove Duplicates from Sorted Array I/II

删除排序数组重复元素,先来个简单的。

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,遍历一次令A[i-k]=A[i]就可以了。看代码:

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n <= 1)
 5             return n;
 6         int k = 0;
 7         for (int i = 1; i < n; ++i) {
 8             if (A[i] == A[i - 1]) {
 9                 ++k;
10             } else if (k > 0) {
11                 A[i-k] = A[i];
12             }
13         }
14         return n - k;
15     }
16 };

题目加些条件:

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

允许重复出现两次。

LZ比较实在,只是老实的把以上代码的A[i]==A[i-1]的条件变成了i > 1 && A[i] ==  A[i-1] && A[i] == A[i-2]

然后果断受教育

Input:[1,1,1,2,2,3]

Output:[1,1,2,3]

Expected:[1,1,2,2,3]

分析原因:A[i-2]有可能不是原来的值了,因为是连续判断3个值,偏移只是偏移1个值,步长不对称。
天真地以为只有这个坑,于是加了个对k的约束,判断条件变成k != 1 && A[i] == A[i - 1] && A[i] == A[i - 2]
果断再次受教育
Input:[1,1,1,1]

Output:[1,1,1]

Expected:[1,1]

该偏移时不偏移了。
好吧,还是好好整理思路吧。
这里加的条件是允许2个,那如果条件逐渐变成允许3个、4个呢?
连写几个比较很明显是不行的,而且还要考虑各种情况,很复杂,设计一个通用的方案更靠谱。
LZ想到的是计数的方法了,记录上一次重复的次数,然后判断次数是否允许,允许则进行偏移,不允许则偏移量加1。
且看代码:
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         int k = 0;
 5         int count = 1;
 6         for (int i = 1; i < n; ++i) {
 7             if (A[i] == A[i - 1]) {
 8                 count++;
 9                 if (count > 2) {
10                     k++;
11                     continue;
12                 }
13             } else {
14                 count = 1;
15             }
16             if (k > 0) 
17                 A[i - k] = A[i];
18         }
19         return n - k;
20     }
21 };

 

转载于:https://www.cnblogs.com/flowerkzj/p/3619490.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值