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]
.
地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
算法:直接看代码:
1 class Solution {
2 public:
3 int removeDuplicates(int A[], int n) {
4 if(n <= 1) return n;
5 int j = 1;
6 for(int i = 1; i < n; ++i){
7 if(A[i] != A[i-1]){
8 A[j++] = A[i];
9 }
10 }
11 return j;
12 }
13 };
第二题:
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]
.
地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
算法:每个元素至少可以有两个。遍历的过程中统计每一个元素出现的次数,然后最多留下其中的两个。代码:
1 class Solution {
2 public:
3 int removeDuplicates(int A[], int n) {
4 if(!A || n <= 2) return n;
5 int j = 0;
6 int i = 0;
7 while(i < n){
8 int count = 1;
9 while(i + count < n && A[i+count] == A[i]){
10 ++count;
11 }
12 A[j++] = A[i++];
13 --count;
14 if(count){
15 A[j++] = A[i++];
16 --count;
17 }
18 i += count;
19 }
20 return j;
21 }
22 };