leetcode--Remove Duplicates from Sorted Array II

来源:互联网 发布:手机透视物体软件 编辑:程序博客网 时间:2024/06/05 14:54

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.csdn.net/crazy__chen/article/details/46425475

原创粉丝点击