首页 > 代码库 > 80. Remove Duplicates from Sorted Array II

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.

链接:

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/#/description

5/31/2017

这道题做了好多遍才对。不应该

 1 public class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if (nums == null || nums.length == 0) return 0;
 4         int copyIndex = 1;
 5         int duplicateCount = 0;
 6         for (int i = 1; i < nums.length; i++) {
 7             if (nums[i - 1] != nums[i]) {
 8                 nums[copyIndex] = nums[i];
 9                 copyIndex++;
10                 duplicateCount = 0;
11             } else {
12                 duplicateCount++;
13                 if (duplicateCount == 1) {
14                     nums[copyIndex] = nums[i];
15                     copyIndex++;
16                 }
17             }
18         }
19         return copyIndex;
20     }
21 }

别人的答案

https://discuss.leetcode.com/topic/17180/3-6-easy-lines-c-java-python-ruby

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

最多k次的一般解

https://discuss.leetcode.com/topic/7673/share-my-o-n-time-and-o-1-solution-when-duplicates-are-allowed-at-most-k-times

 1 int removeDuplicates(int A[], int n, int k) {
 2 
 3             if (n <= k) return n;
 4 
 5             int i = 1, j = 1;
 6             int cnt = 1;
 7             while (j < n) {
 8                 if (A[j] != A[j-1]) {
 9                     cnt = 1;
10                     A[i++] = A[j];
11                 }
12                 else {
13                     if (cnt < k) {
14                         A[i++] = A[j];
15                         cnt++;
16                     }
17                 }
18                 ++j;
19             }
20             return i;
21 }

https://discuss.leetcode.com/topic/46519/short-and-simple-java-solution-easy-to-understand

更多讨论:

https://discuss.leetcode.com/category/88/remove-duplicates-from-sorted-array-ii

80. Remove Duplicates from Sorted Array II