• leetcode-26. Remove Duplicates from Sorted Array


      今天发现一个好东西--leetcode的course ,虽然没有付费的内容会比较少,不过也很不错了。

      第一篇的string讲的是两点法(Two-pointer technique),也就是数据结构课本里常用的快慢指针。原理很简单,但是题目里要用到的stl有点忘了。。

    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

    For example,
    Given input array nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

     两点法的经典应用除了实例里说的反转,还有除重,代码很简单

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if(nums.size() <= 1)
                return nums.size();
            vector<int>::iterator fast = nums.begin()+1;
            vector<int>::iterator slow = nums.begin();
            while(fast != nums.end())
            {
                if(*fast == *slow)
                {
                    nums.erase(fast);
                }
                else
                {
                    ++fast;
                    ++slow;
                }
            }
            return nums.size();
        }
    };

    leetcode能通过,用vs2015不知为何会运行出错。要注意的是vector的erase清楚之后后续元素会往前移动。

     
  • 相关阅读:
    「Poetize10」封印一击
    「Poetize10」能量获取
    vijosP1499炸毁燃料库
    BZOJ3550: [ONTAK2010]Vacation
    总结#3--一类最小割问题
    BZOJ1976: [BeiJing2010组队]能量魔方 Cube
    BZOJ2132: 圈地计划
    BZOJ2127: happiness
    BZOJ1754: [Usaco2005 qua]Bull Math
    920. 会议室
  • 原文地址:https://www.cnblogs.com/tonychen-tobeTopCoder/p/5149889.html
Copyright © 2020-2023  润新知