Remove Duplicates from Sorted Array II Solutions in C++
Number 80
Difficulty Medium
Acceptance 44.0%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/// Author : Hao Chen// Date : 2014-06-29#include <stdio.h>int removeDuplicates(int A[], int n) {if (n<=2) return n;int pos=0;int cnt=1;for (int i=1; i<n; i++){if (A[i] == A[pos]){cnt++;if (cnt==2){A[++pos] = A[i];}}else{cnt=1;A[++pos] = A[i];}}return pos+1;}void printfArray(int A[], int n) {printf("{ ");for (int i=0; i<n; i++){printf("%d ", A[i]);}printf("}\n");}void testSuite(int a[], int n){printfArray(a, n);n = removeDuplicates(a, n);printfArray(a, n);printf("------------------\n");}#define TEST(a) testSuite(a, sizeof(a)/sizeof(int))int main(){int a0[] = {1, 2, 3, 4, 5};TEST(a0);int a1[] = {1, 1, 1};TEST(a1);int a2[] = {1, 2, 2};TEST(a2);int a3[] = {1, 1, 2};TEST(a3);int a4[] = {1, 1, 1, 1};TEST(a4);int a5[] = {1, 1, 1, 2};TEST(a5);int a6[] = {1, 2, 2, 2};TEST(a6);int a7[] = {1, 2, 2, 2, 3 };TEST(a7);int a8[] = {1, 2, 2, 2, 3, 3};TEST(a8);int a9[] = {1,1,1,2,2,3};TEST(a9);int a10[] = {1,1,1,2,2,2};TEST(a10);int a11[] = {1,1,1,1,3,3};TEST(a11);return 0;}
C++ solution by pezy/LeetCode
class Solution {public:int removeDuplicates(int A[], int n) {if (n<3) return n;int size{1};for (int i=2; i<n; ++i)if (A[i] != A[size] || A[i] != A[size-1])A[++size] = A[i];return ++size;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description//// Author : liuyubobobo/// Time : 2016-12-26#include <iostream>#include <vector>using namespace std;/// Ad-Hoc/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:int removeDuplicates(vector<int>& nums) {int i = 0;int j = 0;while(j < nums.size()){int k = nextIndex(nums, j);int len = min( 2, k-j);for(int ii = 0 ; ii < len ; ii ++)nums[i+ii] = nums[j];i += len;j = k;}return i;}private:int nextIndex(const vector<int>& nums, int index){for(int i = index ; i < nums.size() ; i ++)if(nums[i] != nums[index])return i;return nums.size();}};int main() {vector<int> nums1 = {1, 1, 1, 2, 2, 3};cout << Solution().removeDuplicates(nums1) << endl;return 0;}