zoukankan      html  css  js  c++  java
  • LeetCode26:Remove Duplicates from Sorted Array

    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.

    解法一

    stl中有删除反复元素的函数unique。它的作用是移除反复的元素。可是不会改变元素的位置,而且也不会改变容器的属性。比方说容器的长度。以下是它的说明:
    Removes all but the first element from every consecutive group of equivalent elements in the range [first,last).

    The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.

    The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.

    然后搭配distance函数能够返回容器中元素的个数:
    runtime:32ms

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            return distance(nums.begin(),unique(nums.begin(),nums.end()));
        }
    };

    解法二

    假设不能够使用stl中的unique函数。那么能够使用unique函数的思想,定义两个指针。一个指针指向当前元素,另外一个指针指向和当前元素不同的元素。将第二个指针指向的值赋值给第一个指针右移一位后的值。


    runtime:32ms

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int length=nums.size();
            if(length==0||length==1)
                return length;
            int first=0;
            int last=0;
            while(++last<length)
            {
                if(!(nums[first]==nums[last]))
                {
                    nums[++first]=nums[last];
                }
            }
            return first+1;
        }
    };

    附:以下是stl中unique函数的实现代码:

    template <class ForwardIterator>
      ForwardIterator unique (ForwardIterator first, ForwardIterator last)
    {
      if (first==last) return last;
    
      ForwardIterator result = first;
      while (++first != last)
      {
        if (!(*result == *first))  // or: if (!pred(*result,*first)) for version (2)
          *(++result)=*first;
      }
      return ++result;
    }
  • 相关阅读:
    Mac 安装brew的正确姿势
    Jmeter分布式压测及踩坑记录
    Jmeter录制脚本
    mitmproxy使用详解
    Python单元测试框架pytest常用测试报告类型
    基于Java+Spring Boot开源项目JeeSite的Jenkins持续交付介绍
    Maven入门
    Linux Shell 编程基础详解——吐血整理,墙裂推荐!
    使用Jenkins+Blue Ocean 持续构建自动化部署之安卓源码打包、测试、邮件通知
    使用Jenkins+Pipline 持续构建自动化部署之安卓源码打包、测试、邮件通知
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7270235.html
Copyright © 2011-2022 走看看