• Remove Duplicates from Sorted Array


    Description:

    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.

    Code:

     1     int removeDuplicates(vector<int>& nums) {
     2         
     3         size_t n = nums.size();
     4         
     5         if ( n == 0 )
     6             return 0;
     7             
     8         vector<int>::iterator i = nums.begin();
     9         vector<int>::iterator j = nums.begin()+1;
    10         while (j!=nums.end())
    11         {
    12             if (*i == *j)
    13             {
    14                 j = nums.erase(j);
    15             }
    16             else
    17             {
    18                 ++i;
    19                 ++j;
    20             }
    21         }
    22         return nums.size();
    23     }
  • 相关阅读:
    redis 数据库总结
    drf 序列化类总结
    drf 视图类经典总结
    celery 简介
    虚拟环境搭建pip换源
    git 与 svn,简介差别
    redis 数据库简介
    auth 模块
    python的注释与用户交互 基本数据类型
    python入门
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4577319.html
Copyright © 2020-2023  润新知