【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]
.
题解:简单题,用三个游标:next_position,single和current;
- current指向当前考虑的元素;
- next_position指向下一个新元素放置的位置;
- single指向新元素第一次出现的地方;
每次当current和single指向的元素相等时,就把current前移直到current和single不相等;把single指向的元素放到next_position那里,然后next_position++,继续循环。每次current前移的时候要把对应的数组长度减一。
代码如下:
class Solution { public: int removeDuplicates(int A[], int n) { int next_position = 0;// next_postition指向第一个可以被覆盖的元素的前一个元素 int current = 0;// current指向当前考虑的元素 int single = 0;//在第一次遇见某个元素时,就用single指向它,然后移动current int len = n; while(current < n){ single = current; current ++; if(current < n){ while(current < n && A[current] == A[single]){//current和next_position指向的元素重复 current ++; len--; } A[next_position] = A[single]; next_position++; } else{ A[next_position] = A[single]; break; } } return len; } };
在网上搜索了一下,发现自己的代码太麻烦了,只要两个变量next_position和current就可以了:
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if(n == 0) 5 return n; 6 int next_position = 0; 7 for(int current = 1; current < n;current ++){ 8 if(A[next_position] != A[current]){ 9 A[++next_position] = A[current]; 10 } 11 } 12 13 return next_position+1; 14 } 15 };
还有大神用STL的unique和distance实现:
unique(这里只用到它的第一个版本,即用==判断相等的版本):
Defined in header <algorithm>
template< class ForwardIt > ForwardIt unique( ForwardIt first, ForwardIt last );
Removes all consecutive duplicate elements from the range[first, last)
and returns a past-the-end iterator for the new logical end of the range.
从上面的解释可以看到unique主要用来去除连续的重复元素,所以在使用unique之前最好确保数组是有序的。它的返回值是去重后最后一个元素的位置。
distance:
Defined in header <iterator> template< class InputIt > typename std::iterator_traits<InputIt>::difference_type distance( InputIt first, InputIt last ); Returns the number of elements between first and last. The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.
这个函数就是返回first和last之前的元素个数。
实现代码如下:
class Solution { public: int removeDuplicates(int A[], int n) { return distance(A,unique(A,A+n)); } };
以后就算简单题也要搜搜看别人怎么做的,自己做过的题,再看别人的代码,这样才能进步,不会固步自封。
参考:http://zhangxc.com/2013/11/leetcode-remove-duplicates-from-sorted-array
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了