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;
}
原文地址:https://www.cnblogs.com/zhchoutai/p/7270235.html