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

转载于:https://www.cnblogs.com/panini/p/6926966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值