Sunday 7 August 2016

Remove Duplicates from Sorted Array II

Modification of the problem "Remove Duplicates":
What if the duplicates are allowed at most twice in the resulting array?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
int Solution::removeDuplicates(vector<int> &nums) {
    if(nums.size() == 0){
        return 0;
    } 
    int count = 1;
    int j = 1;
    for(int i = 1 ; i < nums.size(); i++){
        if(nums[i] != nums[i - 1]){
            nums[j] = nums[i];
            count = 1;
            j++;
        }
        else if(count == 1){
            nums[j] = nums[i];
            count = 2;
            j++;
        }
    }
    return j;
}
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts