LeetCode: Remove Duplicates from Sorted Array II
2014-04-02 00:00
477 查看
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]
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个 hashmap 来记录出现次数。
方法一
方法二
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]
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个 hashmap 来记录出现次数。
方法一
// LeetCode, Remove Duplicates from Sorted Array II // 时间复杂度 O(n),空间复杂度 O(1) class Solution { public: int removeDuplicates(int A[], int n) { if (n <= 2) return n; int index = 2; for (int i = 2; i < n; i++){ if (A[i] != A[index - 2]) A[index++] = A[i]; } return index; } };
方法二
// LeetCode, Remove Duplicates from Sorted Array II // 时间复杂度 O(n),空间复杂度 O(1) class Solution { public: int removeDuplicates(int A[], int n) { int index = 0; for (int i = 0; i < n; ++i) { if (i > 0 && i < n - 1 && A[i] == A[i - 1] && A[i] == A[i + 1]) continue; A[index++] = A[i]; } return index; } };
相关文章推荐
- Remove Duplicates from Sorted Array II [LeetCode]
- 【LeetCode从零单刷】Remove Duplicates from Sorted Array I & II
- Leetcode 80]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——80. Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- LeetCode刷题(44)--Remove Duplicates from Sorted Array II
- leetcode_080 Remove Duplicates from Sorted Array II
- [Leetcode]Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- leetcode80 Remove Duplicates from Sorted Array II
- [Leetcode] #26#80 Remove Duplicates from Sorted Array I & II
- [Leetcode] Remove Duplicates from Sorted Array II
- 【Leetcode】Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode] 80 Remove Duplicates from Sorted Array II(数组下标操作)
- LeetCode Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II