[LintCode]Remove Duplicates from Sorted Array II
public class Solution {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
// 2015-4-12 待改进
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return 1;
}
int index = 0;
boolean secondSame = true; //关键:与第一题的区别
for (int i = 1; i < nums.length; i++) {
if (nums[index] != nums[i]) {
secondSame = true;
index++;
nums[index] = nums[i];
} else if (secondSame) {
secondSame = false;
index++;
nums[index] = nums[i];
}
}
return index + 1;
}
}
本文介绍了一个数组去重的算法实现,该算法允许每个元素最多出现两次,并返回处理后的数组长度。通过一个布尔变量控制是否保留当前重复元素,适用于有序数组。
350

被折叠的 条评论
为什么被折叠?



