Remove Duplicates from Sorted Array II leetcode java

题目:

 

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

 

题解:

之前是不允许有重复的。

现在是可以最多允许2个一样的元素。

然后删除duplicate,返回长度。

删除duplicate的方法就是指针的操作。具体方法见代码。

 

代码如下:

复制代码
 1     public int removeDuplicates(int[] A) {
 2         if (A.length <= 2)
 3             return A.length;
 4  
 5         int prev = 1; // point to previous
 6         int curr = 2; // point to current
 7  
 8         while (curr < A.length) {
 9             if (A[curr] == A[prev] && A[curr] == A[prev - 1]) {
10                 curr++;
11             } else {
12                 prev++;
13                 A[prev] = A[curr];
14                 curr++;
15             }
16         }
17  
18         return prev + 1;
19     }
复制代码

 Reference:http://www.programcreek.com/2013/01/leetcode-remove-duplicates-from-sorted-array-ii-java/

posted @   爱做饭的小莹子  阅读(1705)  评论(0)    收藏  举报
编辑推荐:
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
阅读排行:
· 使用TypeScript开发微信小程序(云开发)-入门篇
· 没几个人需要了解的JDK知识,我却花了3天时间研究
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 管理100个小程序-很难吗
· 在SqlSugar的开发框架中增加对低代码EAV模型(实体-属性-值)的WebAPI实现支持
点击右上角即可分享
微信分享提示