首页 > 代码库 > Remove Duplicates from Sorted Array II
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。