本文共 783 字,大约阅读时间需要 2 分钟。
问题:
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]
.
两个指针,first指向最后一个非重复元素,last指向未处理的元素的第一位,两个指针都初始化为0。
代码:
class Solution {public: int removeDuplicates(int A[], int n) { int first,last; first = last = 0; if(n == 0) return 0; while(last != n) { if(A[first] == A[last]) { ++last; } else { A[first+1] = A[last++]; ++first; } } return first+1; }};
转载地址:http://tktsi.baihongyu.com/