leetcode - Remove Duplicates from Sorted Array I && II

本文详细介绍了如何通过遍历数组并使用计数器限制元素重复次数来实现数组去重,包括基本去重和允许最多两次重复的进阶案例。采用了一种通用方法,即把数组分为已处理部分和待处理部分,通过循环遍历数组,更新已处理部分,并在过程中应用计数逻辑判断元素是否符合重复次数限制。

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

Remove Duplicates from Sorted Array I

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

 

Remove Duplicates from Sorted Array II

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,将整个数组看成两个部分,前半部分是符合题目要求的数组,后半部分是待探索的数组,设置两个用于遍历的变量index和i,index用于定位前半部分数组的末尾,i用于定位后半部分的数组,在两个部分之间的元素是被剔除的元素

2,同时设置一个变量count用于记录重复次数,再设置一个变量limit用于记录可重复的最大次数,这样一共4种情况,A[index] == A[i]时,count大于limit或者count不大于limit,A[index] != A[i]时,count大于limit或者count不大于limit

3,通过i的遍历,不断将符合题目要求的元素加入到前半部分数组中

代码:

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4 
 5         if (n < 2)
 6         {
 7             return n;
 8         }
 9 
10         const int limit = 2; //I设为1,II设为2
11         int index = 0, i = 1, count = 1;
12 
13         while (i < n)
14         {
15             if (A[index] == A[i])
16             {
17                 ++count;
18                 if (count > limit)
19                 {
20                     ++i;
21                 }
22                 else
23                 {
24                     A[++index] = A[i++];
25                 }
26             }
27             else
28             {
29                 A[++index] = A[i++];
30                 count = 1;
31             }
32         }
33 
34         return index + 1;
35     }
36 };
View Code

 

通过这两个题目,可以总结出一个对数组进行处理的一般性方法(要求空间复杂度为常数),即将整个数组看成两个部分,前一部分是符合要求的,需要用一个变量来定位这个部分,后一部分是待处理的,通过一个变量来定位和遍历,这两部分中间可能有剩余元素(这部分是被处理过不合要求的),通过遍历处理后一部分的元素,将不断扩张前一部分的数组,直到后一部分的元素都遍历完,整个处理过程就结束了

 

转载于:https://www.cnblogs.com/laihaiteng/p/3984493.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值