• No.26 Remove Duplicates from Sorted Array


    Remove Duplicates from Sorted Array

    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.

     Tags: Array Two Pointers

    移除有序数组中的重复数字
    要求:原地移除,不能使用额外空间;返回新数组的长度

    典型的两指针

     1 #include "stdafx.h"
     2 #include <map>
     3 #include <vector>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Solution
     8 {
     9 public:
    10     int removeDuplicates(vector<int> &nums)
    11     {//移除有序数组中的重复数字
    12      //要求:原地移除,不能使用额外空间;返回新数组的长度
    13         int size = nums.size();
    14         if(size <= 1)
    15             return size;
    16 
    17         int index=0;//无重复数字的最后索引
    18         for(int i=1; i<size; i++)
    19         {
    20             if(nums[i] != nums[index])//重复数字,无视
    21                 nums[++index] = nums[i];
    22         }
    23         nums.erase(nums.begin()+index+1,nums.end());
    24         return index+1;
    25     }
    26 };
    27 
    28 int main()
    29 {
    30     Solution sol;
    31     int data[] = {1,1,1,1};
    32     vector<int> test(data,data+sizeof(data)/sizeof(int));
    33     for(const auto &i : test)
    34         cout << i << " ";
    35     cout << endl;
    36     cout<< boolalpha << sol.removeDuplicates(test)<<endl;
    37         for(const auto &i : test)
    38         cout << i << " ";
    39     cout << endl;    
    40 }
     
  • 相关阅读:
    第5章 继承
    第4章 对象和类
    第3章 java的基本程序设计结构
    Java读写properties格式配置文件
    Net学习日记_三层_2
    Net学习日记_三层_1_登录页面总结篇_残缺版
    Net学习日记_三层_1
    Net学习日记_SQL进阶_2
    Net学习日记_SQL进阶_1
    Net学习日记_ADO.Net_3_案例
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4569411.html
Copyright © 2020-2023  润新知