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

num 26

时间:2016-01-18 22:30:22      阅读:219      评论: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.

 

Subscribe to see which companies asked this question

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        vector<int>::size_type it1;
        vector<int>::size_type it2;
        if(nums.size() < 2) return nums.size();
        for(it1=1,it2=0;it1<nums.size();it1++)
        {
            if(nums[it2]!=nums[it1])
            {
                ;
                nums[++it2]=nums[it1];
                
            }
        }
        return it2+1;
    }
};

 若使用STL库的函数,可直接写为return distance(A, unique(A, A + n));

unique()函数是一个去重函数,STL中unique的函数 unique的功能是去除相邻的重复元素(只保留一个),还有一个容易忽视的特性是它并不真正把重复的元素删除。他是c++中的函数,所以头文件要加#include<iostream.h>,具体用法如下:

    int num[100];

   unique(num,mun+n)返回的是num去重后的尾地址,之所以说比不真正把重复的元素删除,其实是,该函数把重复的元素一到后面去了,然后依然保存到了原数组中,然后返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

distance则用于求出迭代器之间的距离。

 

num 26

标签:

原文地址:http://www.cnblogs.com/xds1224/p/5140545.html

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