LeetCode :: Remove Duplicates from Sorted Array II 详细分析
2014-03-24 21:11
375 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
这道题目是前一篇文章的变形版,也是基本没什么知识点可以展开来说,在前一题的基础上引入一个isTwice这样的布尔型来判断是否出现了两次以上,如果出现了两次以上和之前的重复一视同仁,否则和之前的A[i] != A[i - 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].
这道题目是前一篇文章的变形版,也是基本没什么知识点可以展开来说,在前一题的基础上引入一个isTwice这样的布尔型来判断是否出现了两次以上,如果出现了两次以上和之前的重复一视同仁,否则和之前的A[i] != A[i - 1]一视同仁即可。
class Solution { public: int removeDuplicates(int A[], int n) { if (n == 0) return 0; bool isTwice = false; int pos = 0; for (int i = 1; i < n; i++){ if (A[i] == A[i - 1]){ if (!isTwice){ A[++pos] = A[i]; isTwice = true; } } else { A[++pos] = A[i]; isTwice = false; } } return pos + 1;//这里记得加 1 ,因为pos是最后一个有效位的位置下标,下标从0开始,所以长度肯定是要加一的。 } };
相关文章推荐
- LeetCode::Remove Duplicates from Sorted List II [详细分析]
- Leetcode: Remove Duplicates from Sorted Array II 理解分析
- LeetCode :: Remove Duplicates from Sorted Array [详细分析]
- LeetCode: Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II @python
- LeetCode 80: Remove Duplicates from Sorted Array II
- 【LeetCode】 080. Remove Duplicates from Sorted Array II
- Leetcode | Remove Duplicates from Sorted Array I && II
- leetCode---Remove Duplicates from Sorted Array II
- LeetCode80 Remove Duplicates from Sorted Array II
- LeetCode Remove Duplicates from Sorted Array II
- Leetcode Remove Duplicates from Sorted Array II
- leetcode 080 Remove Duplicates from Sorted Array II(难易度:Medium)
- leetcode Remove Duplicates from Sorted Array II
- LeetCode--Remove Duplicates from Sorted Array II
- leetcode Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- leetcode 36: Remove Duplicates from Sorted Array II
- [LeetCode]题解(python):080-Remove Duplicates from Sorted Array II
- [Leetcode][python]Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II