leetcode || 80、Remove Duplicates from Sorted Array II
2015-04-10 16:24
489 查看
problem:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
and A is now
Hide Tags
Array Two
Pointers
题意:对数组进行去重操作,同一元素最多出现2次,返回新数组大小,同时更新数组。
thinking:
(1)先对数组排序
(2)从左往右遍历数组,出现相同元素开始计数,当重复出现次数超过2次时,用后面的元素覆盖多出的元素(数组往前移动)。
code:
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].
Hide Tags
Array Two
Pointers
题意:对数组进行去重操作,同一元素最多出现2次,返回新数组大小,同时更新数组。
thinking:
(1)先对数组排序
(2)从左往右遍历数组,出现相同元素开始计数,当重复出现次数超过2次时,用后面的元素覆盖多出的元素(数组往前移动)。
code:
class Solution { public: int removeDuplicates(int A[], int n) { if(n<3) return n; int i=0; int j=0; sort(A,A+n); while(j<n) { while(j<n&&A[j]==A[++j]); //J定位到最后一个相同元素的下一个位置 if(j-i>2) { int num=j-i-2; //多余的元素的个数 for(int k=0;k<n-j;k++) //往左移动覆盖多余的元素 A[i+2+k]=A[j+k]; j=i+2; //更新j n-=num; //数组减小num } i=j; //更新i } return n; } };
相关文章推荐
- (java)leetcode-80:Remove Duplicates from Sorted Array II
- Leetcode_80_Remove Duplicates from Sorted Array II
- [LeetCode]80 Remove Duplicates from Sorted Array II
- leetcode[80]:Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II - LeetCode 80
- [leetcode 80, Medium] Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II LeetCode
- leetcode-80-Remove Duplicates from Sorted Array II 顺序表
- leetcode-80 Remove Duplicates from Sorted Array II
- [leetcode-80]Remove Duplicates from Sorted Array II(C)
- leetcode-26&80 Remove Duplicates from Sorted Array I & II
- LeetCode 80 Remove Duplicates from Sorted Array II
- LeetCode 80 Remove Duplicates from Sorted Array II
- LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)
- Leetcode_80_Remove Duplicates from Sorted Array II
- leetcode题解-80 Remove Duplicates from Sorted Array II
- leetcode[80] Remove Duplicates from Sorted Array II
- [C语言][LeetCode][80]Remove Duplicates from Sorted Array II
- LeetCode 80: Remove Duplicates from Sorted Array II
- leetcode80 Remove Duplicates from Sorted Array II