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

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

题目

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.

我的想法

双指针,慢指针记录被移动的元素

class Solution {
public int removeDuplicates(int[] nums) {
int letterNums = 1; int prev = 0; for(int i = 1; i < nums.length; i++){
if(nums[i] == nums[prev] && letterNums < 2){
letterNums++; nums[++prev] = nums[i]; } else if(nums[i] != nums[prev]){
nums[++prev] = nums[i]; letterNums = 1; } } return prev+1; }}

解答

leetcode solution 1:

 i-2     i
[ 1, 1, 2, 2, 2 ]
          n
        i-2     i
[1, 1, 2, 2, 2]
                 n

public int removeDuplicates(int[] nums) {
int i = 0; for (int n : nums) if (i < 2 || n > nums[i-2]) nums[i++] = n; return i;}

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

你可能感兴趣的文章
HTTP的长连接和短连接
查看>>
TCP,IP,HTTP,SOCKET区别和联系
查看>>
域名解析过程,很好的一张图收藏了
查看>>
整理时下流行的浏览器User-Agent大全
查看>>
IAAS、SAAS 和 PAAS 的区别、理解
查看>>
RichEdit对ole 对象的相关支持总结
查看>>
(分享)win10下双显示屏独立设置不同缩放率的方法
查看>>
High DPI Settings in Windows
查看>>
几年来的工作与生活感悟
查看>>
切换输入法导致程序死机的解决办法
查看>>
使用ShellExecute打开目标文件所在文件夹并选中目标文件
查看>>
debug下情况良好、release下频繁奔溃问题的跟踪与解析
查看>>
数据透传的概念
查看>>
Wireshark TCP报文到达ACK确认机制
查看>>
一站式学习Wireshark(四):网络性能排查之TCP重传与重复ACK
查看>>
TCP 的那些事儿
查看>>
Wireshark抓包常见问题解析
查看>>
ip头、tcp头、udp头详解及定义,结合Wireshark抓包看实际情况
查看>>
获取在Windows 资源管理器中执行COPY/PASTE的文件列表信息
查看>>
工作中多讨论多交流的益处
查看>>