LeetCode-Remove Duplicates from Sorted Array II (删除重复元素,使重复次数最多N次)
2015-03-07 09:56
711 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
可以先看另外一道题,/article/10984864.html,这个是加强版的。其实仿照上题,改造好的代码如下:
只是在if语句中,加了更严谨的条件判断。
此题可以再加强一下,如果重复元素最后允许出现3次呢?5次呢?或者直接n次?怎么解?可以说思路基本一样,只不过需要判断新数组中重复元素的个数,如果超过n就不需要复制了。上代码:
i和j的含义同上,只不过加了一个s起始位,表示此元素的起始位,用j-s来计算重复元素的个数。
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].
可以先看另外一道题,/article/10984864.html,这个是加强版的。其实仿照上题,改造好的代码如下:
public int removeDuplicates(int[] A) { if (A.length < 3) { return A.length; } int j = 0; for (int i = 1; i < A.length; i++) { if (A[j] != A[i] || (A[j] == A[i] && (j == 0 || A[j] != A[j-1]))) { A[++j] = A[i]; } } return j+1; }
只是在if语句中,加了更严谨的条件判断。
此题可以再加强一下,如果重复元素最后允许出现3次呢?5次呢?或者直接n次?怎么解?可以说思路基本一样,只不过需要判断新数组中重复元素的个数,如果超过n就不需要复制了。上代码:
public int removeDuplicates(int[] A, int n) { if (A.length < n+1) { return A.length; } int j = 0; int s = 0; for (int i = 1; i < A.length; i++) { if (A[j] != A[i]) { A[++j] = A[i]; s = j; } else if (A[j] == A[i] && j - s < n-1) { A[++j] = A[i]; } } return j+1; }
i和j的含义同上,只不过加了一个s起始位,表示此元素的起始位,用j-s来计算重复元素的个数。
相关文章推荐
- LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- LeetCode | Remove Duplicates from Sorted Array II(删除重复的元素2)
- Leetcode刷题记——26. Remove Duplicates from Sorted Array(删除数组重复元素)
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- [Leetcode] Remove duplicates from sorted array 从已排序的数组中删除重复元素
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- Leetcode Remove Duplicates from Sorted List II 删除链表中重复的元素II
- LeetCode | Remove Duplicates from Sorted Array(删除有序数组的重复元素)
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- leetcode:26&80 Remove Duplicates from Sorted Array 删除数组中的重复元素
- leetcode(83)—— 删除已排序链表重复元素(Remove Duplicates from Sorted List)
- LintCode Remove Duplicates from Sorted Array II 删除排序数组中的重复数字 II
- Remove Duplicates from Sorted Array(去掉重复的元素)leetcode
- LeetCode | Remove Duplicates from Sorted List II(删除链表中重复结点2)
- leetcode83---Remove Duplicates from Sorted List(删除重复元素)
- 【leetcode 移除有序序列重复数字】Remove Duplicates from Sorted Array(List) I(II)