首页 > 代码库 > LeetCode --- 26. Remove Duplicates from Sorted Array

LeetCode --- 26. Remove Duplicates from Sorted Array

题目链接: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].

这道题的要求是在有序数组中删除重复元素,使每个数字出现且只出现1次,并返回数组的新的长度。要求:不允许申请额外空间,即要求恒定的空间复杂度。

这道题的思路就是采用两个指针l和r,l记录不重复元素的位置,r从l的下一个开始遍历数组,如果r位置的数字等于l位置的数字,说明该数字重复出现,不予处理;如果r位置的数字不等于l位置的数字,说明该数字没有重复,需要放到l的下一位置,并使l加1。

时间复杂度:O(n)

空间复杂度:O(1)

 1 class Solution
 2 {
 3 public:
 4     int removeDuplicates(int A[], int n)
 5     {
 6         if(n == 0)
 7             return 0;
 8         
 9         int l = 0;
10         for(int r = 1; r < n; ++ r)
11             if(A[r] != A[l])
12                 A[++ l] = A[r];
13         return l + 1;
14     }
15 };

转载请说明出处:LeetCode --- 26. Remove Duplicates from Sorted Array

LeetCode --- 26. Remove Duplicates from Sorted Array