LeetCode: Remove Duplicates from Sorted Array
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]
.
地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
算法:直接看代码:
1 class Solution {
2 public:
3 int removeDuplicates(int A[], int n) {
4 if(n <= 1) return n;
5 int j = 1;
6 for(int i = 1; i < n; ++i){
7 if(A[i] != A[i-1]){
8 A[j++] = A[i];
9 }
10 }
11 return j;
12 }
13 };
第二题:
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]
.
地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
算法:每个元素至少可以有两个。遍历的过程中统计每一个元素出现的次数,然后最多留下其中的两个。代码:
1 class Solution {
2 public:
3 int removeDuplicates(int A[], int n) {
4 if(!A || n <= 2) return n;
5 int j = 0;
6 int i = 0;
7 while(i < n){
8 int count = 1;
9 while(i + count < n && A[i+count] == A[i]){
10 ++count;
11 }
12 A[j++] = A[i++];
13 --count;
14 if(count){
15 A[j++] = A[i++];
16 --count;
17 }
18 i += count;
19 }
20 return j;
21 }
22 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一则复杂 SQL 改写后有感
· golang中写个字符串遍历谁不会?且看我如何提升 50 倍
· C# 代码如何影响 CPU 缓存速度?
· 智能桌面机器人:使用 .NET 为树莓派开发 Wifi 配网功能
· 一则复杂 SQL 改写后有感
· 接口被刷百万QPS,怎么防?
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一个开源免费、功能丰富的 WPF 自定义控件资源库
· 提升Avalonia UI质感,跨平台图标库选型实践