Remove Duplicates from Sorted Array II
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]
.
标签: Array Two Pointers
分析
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个hashmap来记录出现次数。
代码1
#include <iostream> using namespace std; int arr[100]; int removetwoDuplicate(int a[],int n){ int index = 0; if( n <= 2){ index = n; } else{ index = 2; for (int i =2; i < n; i++){ if (arr[index - 2] != arr[i]){ arr[index] = arr[i]; index++; } } } return index; } int main() { int n; cin >> n; for (int i = 0; i < n; i++){ cin >> arr[i]; } int a = removetwoDuplicate(arr,n); cout << a <<endl; for(int i = 0; i < a; i++){ cout << arr[i] << endl; } }
代码2:
#include <iostream> using namespace std; int arr[100]; int main() { int n; cin>>n; for(int i = 0; i < n; i++){ cin >> arr[i]; } int index = 0; int count = 1; if(n > 2 ){ for (int j = 1; j< n; j++){ if(arr[index] != arr[j]){ index += 1; arr[index] = arr[j]; count = 1; } else{ count++; if(count <= 2){ index++; arr[index] = arr[j]; } } } for(int i = 0;i <= index; i++){ cout << arr[i]; } cout << endl; cout << index+1<<endl; } else { for(int i = 0; i < n; i++){ cout << arr[i]<< endl; } cout << n << endl; } return 0; }