• 【LeetCode】080. 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 1122 and 3. It doesn't matter what you leave beyond the new length.

    题解:

    Solution 1 

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int k = 2;
            int n = nums.size();
            if(n < 3)
                return n;
            int index = 0, cnt = 1;
            for(int i = 1; i < n; ++i){
                if(nums[i] != nums[index]){
                    cnt = 1;
                    nums[++index] = nums[i];
                } else if(++cnt <= k){
                    nums[++index] = nums[i];
                }
            }
            return index + 1;
        }
    };

    Solution 2 

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int k = 2;
            int n = nums.size();
            if(n < k)
                return n;
            int index = k;
            for(int i = k; i < n; ++i){
                if(nums[i] != nums[index - k])
                    nums[index++] = nums[i];
            }
            return index;
        }
    };

    此解与Remove Duplicates from Sorted Array相似

  • 相关阅读:
    Android网络通信的六种方式
    launcher4.0加载
    MessageDigest使用 完成MD5加密
    java集合
    Context
    android字库使用
    Java动态代理
    积累
    sql游标
    无限级CSS树形菜单
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7461656.html
Copyright © 2020-2023  润新知