【Leetcode】之Remove Duplicates from Sorted Array II
2016-06-21 11:53
417 查看
一.问题描述
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,
2and
3.
It doesn't matter what you leave beyond the new length.
二.我的解题思路
这道题首先需要理解题意,即需要以复制覆盖的方式来remove duplicate。我的思路是首先建立一个vector,然后遍历一次数组,记录下相邻元素不同的位置并且将这些位置存入vector中。比如对于[1,1,1,2,2,3],那么遍历完一次数组之后,vector中就存放着[-1,2,4,5]其中-1是人为加的,而2,4,5则代表着nums[2]!=nums[2+1]诸如此类。vector中的这些位置下标将数组nums分成了不同的段。接下来就是遍历vector并进行移位覆盖,注意移动的位数是有叠加的。测试通过的程序如下:
class Solution { public: int removeDuplicates(vector<int>& nums) { int len = nums.size(); int res=0; if(len<=2) return len; int i=0; vector<int> record;record.push_back(-1); while(i+1<len){ if(nums[i]!=nums[i+1]) record.push_back(i); i++; } record.push_back(len-1); int rec_len = record.size(); int step=0; for(int i=1;i<rec_len;i++){ int curr_step = (record[i]-record[i-1]<=2)?0:(record[i]-record[i-1]-2); step+=curr_step; if(curr_step==0) res+=record[i]-record[i-1]; else res+=2; int st_idx=record[i]+1; if(st_idx>=len) break; int cnt=0; while(st_idx<=record[i+1] && cnt<2){ nums[st_idx-step]=nums[st_idx]; cnt++; st_idx++; } } return res; } };
相关文章推荐
- Visual Studio VSHOST(承载/宿主进程)
- 合并两个有序单链表
- mysql5.6 二进制免编译安装
- linux下使用yum安装mysql、tomcat、httpd
- 设计模式的六大原则
- java https get
- Android动画之translate(位移动画)
- CakePHP3.2 api 之读写分离
- JAVA和C#之间SOCKET通信的问题
- microsoft setup bootstrapper 已停止工作
- JS实现简单的右下角弹出提示窗口完整实例
- excel 批量格式转换
- Ubuntu下的python的lxml库安装
- linux 最近使用的命令
- mac设置java环境变量, 使用oh-my-zsh
- ROS学习--语义理解NODE(NLU,NLP)
- php 发送验证码到邮箱
- Leetcode 252 meeting rooms
- iOS 类似美团外卖 app 两个 tableView 联动效果实现
- DB2备忘