• 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;
    }
  • 相关阅读:
    videojs播放直播源rtmp时画面在左上角解决方案
    常用git操作命令
    vue使用vue-video-player在直播中的应用
    element-ui隐藏组件scrollbar的使用
    Array.reduce()学习
    阿里云物联网套件(iot)设备间通信(M2M)在web端的实践
    前端axios下载excel(二进制)
    nodejs连接阿里云物联网套件(mqtt)
    base64格式图片转换为FormData对象进行上传
    NodeJS之微信开发
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7270235.html
Copyright © 2020-2023  润新知