美文网首页
Leetcode 80. Remove Duplicates f

Leetcode 80. Remove Duplicates f

作者: persistent100 | 来源:发表于2017-07-14 10:32 被阅读0次

    题目

    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.jianshu.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;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 80. Remove Duplicates f

          本文链接:https://www.haomeiwen.com/subject/losnhxtx.html