zoukankan      html  css  js  c++  java
  • Leetcode题目: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.

    解答:

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int size = nums.size();
            if(size <= 2)
                return size;
            int cur_index = 0;
            int p = 1;
            int q = 2;
            while(q < size)
            {
                if(nums[cur_index] != nums[p])
                {
                    nums[++cur_index] = nums[p++];
                    q = p + 1;
                }
                else
                {
                    if(nums[p] != nums[q])
                    {
                        nums[++cur_index] = nums[p++];
                        q = p + 1;
                    }
                    else
                    {
                        p++;
                        q = p + 1;
                    }
                }
            }
            nums[++cur_index] = nums[p++];
            return cur_index + 1;      
        }
    };

    其中,cur_index一直控制着最终应该返回的只允许两次重复的边界,而p是当前正在判断的数字,q为其下一个数字。

    自己的题解过程,看起来很复杂,其实,仔细一想,只需要一个变量记录当前的位置,需要一个变量来迭代的往后走,判断该变量指向的位置的前两个位置是否与迭代变量所指向的相同。

    优秀答案:

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

  • 相关阅读:
    k阶斐波那契数列fibonacci第n项求值
    PMP学习笔记--03项目范围管理
    PMP学习笔记--02项目整合管理
    PMP学习笔记--01项目管理概论
    Java学习笔记 -- 头代码
    Scrum Framework, Process and Story Point
    敏捷宣言(Agile Manifesto)和敏捷开发十二原则
    如何将excel文件导入testlink
    Robot Framework环境搭建
    Fiddler抓包工具的使用
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5186327.html
Copyright © 2011-2022 走看看