zoukankan      html  css  js  c++  java
  • Leetcode: 80. Remove Duplicates from Sorted Array II

    Description

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

    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.
    

    思路

    • 两个指针,一个指向原数组,一个指向新数组,然后一个计数器,在每一次相邻元素不同的时候更新

    代码

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int len = nums.size();
            if(len == 0) return 0;
            
            int index = 0, count = 1;
            for(int i = 1; i < len; ++i){
                if(nums[i] != nums[i - 1]){
                    count = 1;
                    index++;
                    nums[index] = nums[i]; //直接覆盖,不要交换,交换会有bug
                }
                else{
                    if(count < 2){
                        index++;
                        count++;
                        nums[index] = nums[i];
                    }
                }
            }
            
            return index + 1;
        }
    };
    
  • 相关阅读:
    drf 三大认证详解
    管理表页面的创建
    电脑自动关机设置
    jwt 认证规则
    视图家族练习
    JQuery 数组获取和删除元素
    JQurey 添加和删除元素
    Java 占位符
    Redis
    线程
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6931247.html
Copyright © 2011-2022 走看看