Leetcode OJ: Remove Duplicates from Sorted Array I/II
删除排序数组重复元素,先来个简单的。
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,遍历一次令A[i-k]=A[i]就可以了。看代码:
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if (n <= 1) 5 return n; 6 int k = 0; 7 for (int i = 1; i < n; ++i) { 8 if (A[i] == A[i - 1]) { 9 ++k; 10 } else if (k > 0) { 11 A[i-k] = A[i]; 12 } 13 } 14 return n - k; 15 } 16 };
题目加些条件:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?For example,
Given sorted array A =[1,1,1,2,2,3]
,Your function should return length =
5
, and A is now[1,1,2,2,3]
.
允许重复出现两次。
LZ比较实在,只是老实的把以上代码的A[i]==A[i-1]的条件变成了i > 1 && A[i] == A[i-1] && A[i] == A[i-2]
然后果断受教育
Input:[1,1,1,2,2,3]
Output:[1,1,2,3]
Expected:[1,1,2,2,3]
Input:[1,1,1,1]Output:[1,1,1]
Expected:[1,1]
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 int k = 0; 5 int count = 1; 6 for (int i = 1; i < n; ++i) { 7 if (A[i] == A[i - 1]) { 8 count++; 9 if (count > 2) { 10 k++; 11 continue; 12 } 13 } else { 14 count = 1; 15 } 16 if (k > 0) 17 A[i - k] = A[i]; 18 } 19 return n - k; 20 } 21 };