题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/
题目:
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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
解题思路:
这题比较简单,维护一个对相同数字的计数值,当计数值大于 2 时,就跳过该元素。
同时,还要维护一个存放当前元素的下标位置,由于前面的元素可能存在计数值大于 2 的情况,遂要把后面的元素往前挪。
特别指出,题目只关心挪动元素后新数组的前 length 个元素
代码实现:
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int n = 1;
int tempN = 1;
int index = 0;
for(int i = 1; i < nums.length; i ++) {
if(nums[i] != nums[i - 1]) {
n ++;
tempN = 1;
nums[++ index] = nums[i];
} else {
if(tempN < 2) {
n ++;
nums[++ index] = nums[i];
}
tempN ++;
}
}
return n;
}
}
164 / 164 test cases passed.
Status: Accepted
Runtime: 2 ms