zoukankan      html  css  js  c++  java
  • 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清楚之后后续元素会往前移动。

     
  • 相关阅读:
    Python学习之旅—生成器对象的send方法详解
    对集合多列进行求和方法的选择
    23种设计模式
    这一天,我真正的体会到。。。
    火狐浏览器导出EXCEL 表格,文件名乱码问题
    K-fold Train Version3
    K-fold Train Version2
    K-fold Train
    Confusion matrix
    Kaggle Solutions
  • 原文地址:https://www.cnblogs.com/tonychen-tobeTopCoder/p/5149889.html
Copyright © 2011-2022 走看看