zoukankan      html  css  js  c++  java
  • 【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相似

  • 相关阅读:
    日期帮助类
    校验帮助类
    缓存帮助类
    数据转换帮助类
    枚举帮助类
    sql 不常用的知识点记录
    反射实例化不同类型的实例
    xml读取
    读取字段别名
    动态类型赋值处理
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7461656.html
Copyright © 2011-2022 走看看