码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode26:Remove Duplicates from Sorted Array

时间:2015-07-06 18:05:48      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode26:Remove Duplicates from Sorted Array

标签:

原文地址:http://blog.csdn.net/u012501459/article/details/46775541

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!