zoukankan      html  css  js  c++  java
  • LeetCode | Remove Duplicates from Sorted Array

    Remove Duplicates from Sorted Array

     Total Accepted: 61826 Total Submissions: 196575My Submissions

    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.

    Show Tags














    做法:set存不重复的值,清空原来的vector,再把set对象copy进vector对象里去,主要是copy。

    代码:

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums){
           set<int> temp(nums.begin(),nums.end());
           nums.clear();
           nums.resize(temp.size());
           std::copy(temp.begin(), temp.end(), nums.begin());
           return temp.size();
        }
    };

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    124. 二叉树中的最大路径和
    快速排序,归并排序
    剑指offer ——重建二叉树
    共享指针的简单实现
    string_自定义
    幸运的袋子
    动态规划——出差问题
    计算数组平均值
    时间格式化并算差值
    适配器模式
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965328.html
Copyright © 2011-2022 走看看