Remove Duplicates from Sorted Array
2013.12.7 03:29
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]
.
Solution:
The array is sorted, so duplicates must be in a consecutive group. Here I used two pointers, one to scan the array, the other to record the unique value. Everytime a unique value is found, record it. The rest of the duplicate values are discarded and overwritten.
Time complexity is O(n), space complexity is O(1).
Accepted code:
1 //#define __MAIN__ 2 #include <cstdio> 3 #include <cstdlib> 4 using namespace std; 5 6 class Solution { 7 public: 8 int removeDuplicates(int A[], int n) { 9 // Note: The Solution object is instantiated only once and is reused by each test case. 10 int i, j, k; 11 12 i = 0; 13 k = 0; 14 while(i < n){ 15 j = i + 1; 16 while(j < n && A[i] == A[j]){ 17 ++j; 18 } 19 A[k] = A[i]; 20 ++k; 21 i = j; 22 } 23 24 return k; 25 } 26 }; 27 28 #ifdef __MAIN__ 29 int main() 30 { 31 Solution sol; 32 int A[] = {1}; 33 const int n = sizeof(A) / sizeof(int); 34 int len; 35 36 len = sol.removeDuplicates(A, n); 37 printf("%d\n", len); 38 for(int i = 0; i < len; ++i){ 39 printf("%d ", A[i]); 40 } 41 printf("\n"); 42 43 return 0; 44 } 45 #endif
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)