LeetCode 80. Remove Duplicates from Sorted Array II (从有序序列里移除重复项之二)
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array 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
. It doesn't matter what you leave beyond the new length.
题目标签:Array
这道题目和之前的区别就是,可以保留第二个重复的数字。基本想法都和前一题一样,在这里只要多加一个int count 来记录这是第几个重复的number,如果是第二个的话,把pointer 往右移动一格,并且把nums[i] 的值 复制到 nums[pointer],然后count++。除此之外,还需要在遇到不同数字的情况里,加上,count = 1, 因为一旦遇到不同的数字,那么count 计数又要重新开始了。详细可以看代码,和之前那题代码的比较。
Java Solution:
Runtime beats 27.80%
完成日期:07/29/2017
关键词:Array
关键点:多设一个int count 来记录出现重复数字的次数
1 public class Solution 2 { 3 public int removeDuplicates(int[] nums) 4 { 5 if(nums.length <= 2) 6 return nums.length; 7 8 int pointer = 0; 9 int count = 1; 10 11 for(int i=1; i<nums.length; i++) 12 { 13 // if this number is different than pointer number 14 if(nums[i] != nums[pointer]) 15 { 16 pointer++; 17 nums[pointer] = nums[i]; 18 count = 1; 19 } 20 else // if this number is same as pointer number 21 { 22 if(count == 1) // if it is second same number 23 { 24 pointer++; 25 nums[pointer] = nums[i]; 26 count++; 27 } 28 } 29 } 30 31 return pointer + 1; 32 } 33 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?