Leetcode -- Remove Duplicates from Sorted Array II
来源:互联网 发布:linux 修改密码 编辑:程序博客网 时间:2024/04/25 11:44
https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
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].
这一题和Remove Duplicate from Sorted Array其实没有本质的不同,都是依赖快慢指针实现,只是这一题需要再加一个当前数值的计数器,当超过2的时候慢指针就不再前进了。难度不高,时间O(N) 空间O(1)
public int removeDuplicates(int[] A) { if(A.length == 0) return 0; int curval = A[0]; int cur_counter = 1; int counter = 1; for(int i = 1; i < A.length; i++){ if(A[i] == curval){ cur_counter++; counter = cur_counter <= 2 ? counter + 1 : counter; }else{ curval = A[i]; counter++; cur_counter = 1; } A[counter - 1] = curval;//虽然每次都在赋值,但实际上当cur_counter > 2的时候counter维持原地,这样写只是为了代码看起来更简洁。 } return counter; }
0 0
- 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] 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-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 | 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] Remove Duplicates from Sorted Array II
- Leetcode Remove Duplicates from Sorted Array II
- 用立异,声东击西——贵阳Flex创客团队航行器吸引世界眼光
- 【BZOJ 1042】 [HAOI2008]硬币购物
- 微信公众平台开发 无高级接口账号获取用户基本信息
- 在项目中,过滤器如何配置?可以实现拦截!
- windows下gvim的配置文件
- Leetcode -- Remove Duplicates from Sorted Array II
- BestCoder Round #28
- iOS平台(移动平台)架构问题
- HDU2519 新生晚会【水题】【组合数】
- 专车:一边点赞,一边釜底抽薪;前路难探,内部利益出现分化
- 错误隐藏学习手记(一)
- Spring学习 8
- Spring学习 9
- 年终大学习之MySQL数据库优化学习笔记(五)