Remove Duplicates from Sorted Array II
Posted 三公分阳光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Remove Duplicates from Sorted Array II相关的知识,希望对你有一定的参考价值。
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; }
以上是关于Remove Duplicates from Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 26. Remove Duplicates from Sorted Array 80. Remove Duplicates from Sorted Array II
26. Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array