leetcode--Remove Duplicates from Sorted Array II

本文介绍了一种解决LeetCode中移除排序数组中重复元素的问题的方法,通过双指针技术确保每个元素最多只出现两次。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 ofnums being 1122 and3. It doesn't matter what you leave beyond the new length.


题意:移除排序数组中的重复元素,一个元素最多出现两次

分类:数组,双指针


解法1:和leetcode--Remove Duplicates from Sorted Array一样,使用双指针,但是每次覆盖时,判断是否由两个以上重复,如果是,覆盖两次,否则覆盖一次

[java]  view plain  copy
  1. public class Solution {  
  2.    public int removeDuplicates(int[] nums) {  
  3.         int cur = Integer.MIN_VALUE;  
  4.         int count = 0;  
  5.         int sum = 0;  
  6.         for(int i=0;i<nums.length;i++){  
  7.             if(cur==nums[i]){  
  8.                 if(count==1){  
  9.                     nums[sum] = nums[i];   
  10.                     count++;  
  11.                     sum++;                    
  12.                 }else{                        
  13.                     count = 0;  
  14.                     cur = nums[i];                    
  15.                 }  
  16.             }else{  
  17.                 cur = nums[i];  
  18.                 nums[sum] = nums[i];   
  19.                 sum++;  
  20.                 count = 1;  
  21.             }             
  22.         }  
  23.         return sum;  
  24.     }  
  25.   
  26. }  

[java]  view plain  copy
  1. public class Solution {  
  2.     public int removeDuplicates(int[] nums) {  
  3.         int count = 0;  
  4.         int len = nums.length;  
  5.         if(len==0return 0;  
  6.         int pre = 0;  
  7.         int cur = 0;  
  8.         while(cur<len){  
  9.             if(nums[cur]==nums[pre]){  
  10.                 cur++;  
  11.             }else{  
  12.                 nums[count++] = nums[pre];  
  13.                 if(cur-pre>=2){  
  14.                     nums[count++] = nums[pre];  
  15.                 }  
  16.                 pre = cur;  
  17.             }  
  18.         }  
  19.         nums[count++] = nums[cur-1];  
  20.         if(cur-pre>=2){  
  21.             nums[count++] = nums[cur-1];  
  22.         }  
  23.         return count;  
  24.     }  
  25. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46425475

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值