zoukankan      html  css  js  c++  java
  • 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 }
     
  • 相关阅读:
    Linux
    bzoj 1834
    bzoj 1002 找规律(基尔霍夫矩阵)
    bzoj 1005 组合数学 Purfer Sequence
    bzoj 1601 最小生成树
    bzoj 1001 平面图转对偶图 最短路求图最小割
    bzoj 1192 二进制
    bzoj 1012 基础线段树
    bzoj 1044 贪心二分+DP
    bzoj 1011 近似估计
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4569411.html
Copyright © 2011-2022 走看看