Remove duplicates from Sorted Array II
Follow up for "Remove duplicates":
What if duplicates is allowed at the 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]
.
Tags: Array of pointers
Analysis
Add a variable to record the number of occurrences of the element. This is because it is a sorted array, so a variable can be solved. If there is no sorted array, you need to introduce a hashmap to record the number of occurrences.
Code 1
#include <iostream>using namespacestd;intarr[ -];intRemovetwoduplicate (intA[],intN) { intindex =0; if(N <=2) {Index=N; } Else{Index=2; for(inti =2; I < n; i++){ if(Arr[index-2] !=Arr[i]) {Arr[index]=Arr[i]; Index++; } } } returnindex;}intMain () {intN; CIN>>N; for(inti =0; I < n; i++) {cin>>Arr[i]; } intA =removetwoduplicate (arr,n); cout<< a <<Endl; for(inti =0; i < A; i++) {cout<< Arr[i] <<Endl; }}
Code Listing 2:
#include <iostream>using namespacestd;intarr[ -];intMain () {intN; CIN>>N; for(inti =0; I < n; i++) {cin>>Arr[i]; } intindex =0; intCount =1; if(N >2 ){ for(intj =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(inti =0; I <= index; i++) {cout<<Arr[i]; } cout<<Endl; cout<< index+1<<Endl; } Else { for(inti =0; I < n; i++) {cout<< arr[i]<<Endl; } cout<< N <<Endl; } return 0;}
Remove duplicates from Sorted Array II