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

 

Note: copied from others. It's a general solution.

 

 1 public class Solution {
 2     public int RemoveDuplicates(int[] nums) {
 3         return RemoveKDuplicates(nums, 2);
 4     }
 5     
 6     private int RemoveKDuplicates(int[] nums, int k) {
 7         if (nums.Length <= k) return nums.Length;
 8         
 9         int i = 1, j = 1, count = 1;
10         while (j < nums.Length)
11         {
12             if (nums[j] != nums[j - 1])
13             {
14                 count = 1;
15                 nums[i++] = nums[j];
16             }
17             else if (count < k)
18             {
19                 count++;
20                 nums[i++] = nums[j];
21             }
22             
23             j++;
24         }
25         
26         return i;
27     }
28 }

 

posted @ 2017-11-13 05:11  逸朵  阅读(119)  评论(0)    收藏  举报