随笔- 509  文章- 0  评论- 151  阅读- 22万 

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
复制代码

 

 posted on   zhuli19901106  阅读(180)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示