• num 26


    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则用于求出迭代器之间的距离。

  • 相关阅读:
    uva 11355(极角计算)
    hdu 1029(hash)
    hdu 1024(dp)
    SPOJ DISUBSTR(字符串hash)
    SPOJ DISUBSTR(后缀数组)
    【Leetcode】Evaluate Reverse Polish Notation
    【Leetcode】Reverse Words in a String
    【Leetcode】Maximum Product Subarray
    【Leedcode】Insertion Sort List
    【Leetcode】Sort List
  • 原文地址:https://www.cnblogs.com/xds1224/p/5140545.html
Copyright © 2020-2023  润新知