[Lintcode] Remove Duplicates from Sorted Array II
2016-02-24 22:54
316 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
与第一道题大体一致,只需额外引入一个变量标记是否是第二次出现即可
public class Solution {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int index = 0;
boolean twice = false;
for(int i = 1; i < nums.length; i++) {
if(nums[index] != nums[i] || !twice) {
if(nums[index] == nums[i]) {
twice = true;
}
else {
twice = false;
}
nums[index + 1] = nums[i];
index++;
}
}
return index + 1;
}
}
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
[1,1,1,2,2,3],
Your function should return length =
5, and A is now
[1,1,2,2,3].
与第一道题大体一致,只需额外引入一个变量标记是否是第二次出现即可
public class Solution {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int index = 0;
boolean twice = false;
for(int i = 1; i < nums.length; i++) {
if(nums[index] != nums[i] || !twice) {
if(nums[index] == nums[i]) {
twice = true;
}
else {
twice = false;
}
nums[index + 1] = nums[i];
index++;
}
}
return index + 1;
}
}
相关文章推荐
- LintCode Majority Number iii
- LintCode-最大数
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- LintCode 更新二进制位
- Lintcode 二叉树的后序遍历
- Lintcode 二叉树中序遍历
- Lintcode 二叉树前序遍历
- Lintcode 尾部零的个数
- Lintcode 比较字符串
- Lintcode 主元素
- Lintcode解题笔记 - 岛屿的个数
- LintCode -合并两个排序链表