博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
80. Remove Duplicates from Sorted Array II
阅读量:6677 次
发布时间:2019-06-25

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

Given a sorted array nums, remove the duplicates in-place 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 in-place 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]);}

难度:medium

题目:给定一排序的数组,原地删除重复的元素每个元素最多允许出现两次,返回该数组的长度。

思路:给数组设定一个置换元素的下标,和一个计数器

Runtime: 6 ms, faster than 95.30% of Java online submissions for Remove Duplicates from Sorted Array II.

Memory Usage: 39.6 MB, less than 1.01% of Java online submissions for Remove Duplicates from Sorted Array II.

class Solution {    public int removeDuplicates(int[] nums) {        if (nums.length <= 2) {            return nums.length;        }                int cnt = 0, idx = 0, v = nums[0];        for (int i = 0; i < nums.length; i++) {            if (cnt < 2 && nums[i] == v) {                cnt += 1;                nums[idx++] = v;            }                        if (nums[i] != v) {                cnt = 1;                v = nums[i];                nums[idx++] = v;            }        }        return idx;    }}

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

你可能感兴趣的文章
C# ACCESS数据库操作类
查看>>
详解vue通过NGINX部署在子目录或者二级目录实践
查看>>
括号匹配算法思想
查看>>
HDU 1043 Eight 【经典八数码输出路径/BFS/A*/康托展开】
查看>>
589. N叉树的前序遍历
查看>>
Java线程池使用和常用参数(待续)
查看>>
java 中 get post
查看>>
Hive学习之Locking
查看>>
关于Lucene全文检索相关技术
查看>>
简单理解冒泡排序
查看>>
halcon算子翻译——fuzzy_measure_pairing
查看>>
Vertex and FragmentShader顶点与片段着色器
查看>>
Python体验(10)-图形界面之计算器
查看>>
debian9 开启rc.local服务
查看>>
Java时间日期格式转换
查看>>
304444数据库备份和恢复
查看>>
Unity3D 游戏开发应用篇——每日登陆(持久化类实现)
查看>>
Spring Security + OAuth系统环境搭建(一)
查看>>
在XenServer上更改Win7 64bit模板的内存
查看>>
二维数组和二维指针在CUDA中的应用
查看>>