博客
关于我
80. Remove Duplicates from Sorted Array II
阅读量:414 次
发布时间:2019-03-06

本文共 1592 字,大约阅读时间需要 5 分钟。

Given a sorted array nums, remove the duplicates  such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array  with O(1) extra memory.

Example 1:

Given nums = [1,1,1,2,2,3],Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)int len = removeDuplicates(nums);// any modification to nums in your function would be known by the caller.// using the length returned by your function, it prints the first len elements.for (int i = 0; i < len; i++) {    print(nums[i]);}
 

AC code:

class Solution {public:    int removeDuplicates(vector
& nums) { int i = 0; for (auto n : nums) { if (i < 2 || n > nums[i-2]) nums[i++] = n; } return i; }};
Runtime: 
8 ms, faster than 100.00% of C++ online submissions for Remove Duplicates from Sorted Array II.

 

 

转载地址:http://uzxuz.baihongyu.com/

你可能感兴趣的文章
html5 Game开发系列文章之 零[开篇]
查看>>
为什么阿里巴巴建议集合初始化时,指定集合容量大小
查看>>
原创 | 我被面试官给虐懵了,竟然是因为我不懂Spring中的@Configuration
查看>>
为什么阿里巴巴要求谨慎使用ArrayList中的subList方法
查看>>
Redis不是一直号称单线程效率也很高吗,为什么又采用多线程了?
查看>>
基于Python的Appium环境搭建合集
查看>>
Requests实践详解
查看>>
接口测试简介
查看>>
Golang Web入门(4):如何设计API
查看>>
让sublime实现js控制台(前提是安装了nodejs)
查看>>
树莓派连接二手液晶屏小记
查看>>
error: 'LOG_TAG' macro redefined
查看>>
android10Binder(一)servicemanager启动流程
查看>>
ES6基础之——new Set
查看>>
nodeJS实现识别验证码(tesseract-ocr+GraphicsMagick)
查看>>
玩玩小爬虫——试搭小架构
查看>>
AS与.net的交互——加载web上的xml
查看>>
Javascript之旅——第八站:说说instanceof踩了一个坑
查看>>
Javascript之旅——第九站:吐槽function
查看>>
Javascript之旅——第十一站:原型也不好理解?
查看>>