【leetcode】【80】Remove Duplicates from Sorted Array II
来源:互联网 发布:cda数据分析师教程 编辑:程序博客网 时间:2024/05/02 00:01
一、问题描述
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一样,说明还是把后边的满足条件的数字往前挪。鉴于该题要求相同数字不能超过两次,显然如果还和Remove Duplicates一样使用一个指针来遍历很难满足要求,那么我们可以考虑双指针方法。从这个例子[1,1,1,2,2,3]来分析,前两个元素不需要管,从第三个数字来看,我们可以设置两个指针pre,cur,将cur指向第三个元素,将pre指向第二个元素,显然只有当nums[cur]==nums[pre]&&nums[cur]==nums[pre-1]的时候我们需要将cur继续往后移动寻找不同的元素;这时nums[cur]==2,不满足之前的判断条件,那么需要将2覆盖pre之后的元素,所以数组变为了[1,1,2,2,2,3],这时pre指向第一个2,cur指向第三个2,继续执行判断条件,pre可以++,这时虽然讲第三个2覆盖了第二个2因为是循环随意可能会出现同值覆盖的情况,然后继续执行后面的。有点啰嗦,看代码。
三、Java AC代码
public int removeDuplicates(int[] nums) { if (nums.length <= 2) return nums.length; int prev = 1; // point to previous int curr = 2; // point to current while (curr < nums.length) { if (nums[curr] == nums[prev] && nums[curr] == nums[prev - 1]) { curr++; } else { prev++; nums[prev] = nums[curr]; curr++; } } return prev + 1; }
- 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
- Leetcode: Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- 注解添加事务小记
- 自己对volley http模块的二次封装的使用
- performSelectorInOC 使用文档
- [iOS]UICollectionView循环滚动功能的实现思路
- 技术分享
- 【leetcode】【80】Remove Duplicates from Sorted Array II
- 静态代码扫描--Clang Static Analyze
- 电脑svchost netsvc占用内存过大
- 基于wheel的省市县,界面实现优化
- Spring框架
- C语言_函数指针
- 静态代码扫描--OCLint
- nw.js node-webkit系列(15)如何使用内部模块和第三方模块进行开发
- 直方图匹配