Leetcode 80. Remove Duplicates from Sorted Array II

題目

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

分析

從已排序數組中去除重復數字,但最多可以重復兩次。利用上一題的思路:http://www.lxweimin.com/p/2ea74e4e2f4c
就是需要判斷兩次,先判斷和前個是否相同,之后判斷再前面一個是否相同。

int removeDuplicates(int* nums, int numsSize) {
    int length=1;
    if(numsSize==0||numsSize==1)return numsSize;
    if(nums[0]==nums[1])length=2;
    for(int i=length;i<numsSize;i++)
    {
        if(nums[i]!=nums[length-1]||(nums[i]==nums[length-1]&&nums[i]!=nums[length-2]))
        {
            nums[length]=nums[i];
            length++;
        }
    }
    if(numsSize==0)return 0;
    else return length;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容