[LeetCode] 80. Remove Duplicates from Sorted Array II
来源:互联网 发布:设计发型软件 编辑:程序博客网 时间:2024/05/29 04:30
【原题】
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
【解释】
作为删除数组中重复元素的进化版,要求最后目标数组中最多只能有每个元素最多重复两次。
【思路】
在Remove Duplicates from Sorted Array一题中,我们只需要记录目标数组下一个该插入的位置,让后续符合要求的元素插入该位置即可。利用同样的思想,只是在比较的时候不是和前一个元素比较,而是前两个元素。
public int removeDuplicates(int[] nums) { int pos=0;//记录下一个插入的位置 for(int i=0;i<nums.length;i++){ if(i<2||nums[i]>nums[pos-2])//和前两个元素比较 nums[pos++]=nums[i]; } return pos;//犹豫pos从零开始,所以最后即为目标数组的长度 }
阅读全文
0 0
- leetcode——26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II
- LeetCode 26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II
- leetcode.array--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] 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
- [SLAM项目]
- caffe利用anaconda配置python接口(cpu版可视化工具)
- 内插函数恢复模拟信号
- stm8s电机库vtimer_SetTimer()函数的使用
- c#读取Excel中代码到dataGridView中
- [LeetCode] 80. Remove Duplicates from Sorted Array II
- linux信号实现机制详解
- 对n做反运算:!n
- 【Keras学习笔记】-Autoencoding
- Paint:xfermode的使用
- 如何以管理员身份运行Dos窗口
- cJSON 使用笔记
- java 入门
- 阿里云ECS部署:nginx+MySQL+Laravel+PHP7+Redis+Node.js