前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关关的刷题日记07——Leetcode 26. Remove Duplicates from Sorted Array 方法1

关关的刷题日记07——Leetcode 26. Remove Duplicates from Sorted Array 方法1

作者头像
WZEARW
发布2018-04-08 17:47:31
5900
发布2018-04-08 17:47:31
举报
文章被收录于专栏:专知专知专知

关小刷刷题07 – Leetcode 26. Remove Duplicates from Sorted Array 方法1

题目

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.

题目的意思是:排好序的数组中会有一些重复的数,要在不额外开辟空间的情况下删掉重复的数,返回不重复的数的长度。至于新长度之外还有哪些数就不用管了。

方法1

方法1:在关小刷刷题05 – Leetcode 217. Contains Duplicate中,有没有发现unique是个好东西?又能去重,又能直接返回新长度啊。Unique时间复杂度O(n)。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return unique(nums.begin(), nums.end())-nums.begin();
    }
};

方法2

方法2:如果面试的时候不让用unique怎么办呢,那就把不重复的数一点点往前搬了,我是一个小小搬运工,我搬呀搬呀搬。顺便把搬了多少数记录下来,返回。且听下回分解。

人生没有白走的路,每一步都算数,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-10-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 关小刷刷题07 – Leetcode 26. Remove Duplicates from Sorted Array 方法1
    • 题目
      • 方法1
        • 方法2
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档