[LeetCode]Remove Duplicates from Sorted Array II
2014-05-07 14:57
471 查看
题目描述
Follow up for "Remove Duplicates":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].
给定一排好序的数组,将其元素重复多于2的部分删除,返回新数组的长度
解题思路
我们只需分段求解,记录每一段元素的个数,对个数>=2和<2进行讨论,同时使用一个变量lastPos(初始值为0)来记录上一个无重复元素的位置:Duplicates>=2: A[lastPos] = compareVal; A[lastPos + 1] = compareVal; lastPos += 2;
Duplicates<2: A[lastPos] = compareVal; lastPos += 1;
代码
public static int removeDuplicates(int[] A) { if (A == null || A.length == 0) return 0; if (A.length == 1) return 1; int dup = 0; int lastPos = 0; int compareVal; for (int i = 0; i < A.length;) { dup = 0; compareVal = A[i]; while (i < A.length && A[i] == compareVal) { i++; dup++; } if(dup >= 2){ A[lastPos] = compareVal; A[lastPos + 1] = compareVal; lastPos += 2; } else { A[lastPos] = compareVal; lastPos += 1; } } return lastPos; }
相关文章推荐
- LeetCode_Remove Duplicates from Sorted Array II
- leetcode 080 Remove Duplicates from Sorted Array II(难易度:Medium)
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II [080]
- Leetcode_80_Remove Duplicates from Sorted Array II
- Leetcode: 80. Remove Duplicates from Sorted Array II
- LeetCode() Remove Duplicates from Sorted Array II
- LeetCode OJ Remove Duplicates from Sorted Array II
- 【leetcode】【40%】【M】Remove Duplicates from Sorted Array II
- 【Leetcode】【Medium】Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- [LeetCode-80] Remove Duplicates from Sorted Array II
- leetcode80 Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II -- LeetCode
- LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2
- 65_leetcode_remove Duplicates from sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- LeetCode @ Remove Duplicates from Sorted ArrayII 数组去重II