zoukankan      html  css  js  c++  java
  • 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则用于求出迭代器之间的距离。

  • 相关阅读:
    java jpg图片按质量保存
    Python 九九乘法表
    Linux 磁盘空间查看
    jsTree 隐藏父节点的复选框;只留最底一层的复选框
    padding-top实现列表图片自适应
    jsTree自定义contextmenu 的二种方式
    jstree插件对树操作增删改查的使用
    layui遇到的坑
    layui复选框全选,单选取消全选
    获取 Layui 表单 select 中的 option 的自定义属性
  • 原文地址:https://www.cnblogs.com/xds1224/p/5140545.html
Copyright © 2011-2022 走看看