[算法分析与设计] leetcode 每周一题: 80. Remove Duplicates from Sorted Array II
来源:互联网 发布:淘宝买的战地1激活码 编辑:程序博客网 时间:2024/05/20 05:44
题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/
题目 :
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.
思路:
本题没什么难度,唯一需要注意的地方是,不但要返回长度length,也要更改数组(因为我直接从·II开始做,
没做一,不知道要改,卡了挺久。。。)主要思路就是维护三个状态,一个是计数器count,一个是目前长度
len,一个是对比字id,然后从前往后遍历,当id一样且次数少于2时候,count+1,len+1,同时数组nums[len]
= 字符,当对比字符不一致时候,重置对比字符,count+1,len+1,同时数组nums[len] = 字符, id一样且次
数已经达到2次,不做处理,跳过
代码如下:
class Solution {public: int removeDuplicates(vector<int>& nums) { if(nums.size() == 0) return 0; int count = 0; int id = nums[0]; int len = 0; for(int i = 0; i < nums.size(); i++) { if(id == nums[i] && count <= 1) { count ++; } else if(id != nums[i]) { count = 1; id = nums[i]; } else { continue; } nums[len++] = nums[i]; } return len; }};
阅读全文
0 0
- [算法分析与设计] leetcode 每周一题: 80. Remove Duplicates from Sorted Array II
- LeetCode---Remove Duplicates from Sorted Array、Remove Duplicates from Sorted Array II解题分析
- LeetCode :: Remove Duplicates from Sorted Array II 详细分析
- Leetcode: Remove Duplicates from Sorted Array II 理解分析
- 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算法题目: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
- 第13周项目1(2)-验证分块查找算法
- ionic 购物车
- 为什么在BMP图片中,像素的排布为BGR
- NFS
- Spring Boot项目的真实程序入口
- [算法分析与设计] leetcode 每周一题: 80. Remove Duplicates from Sorted Array II
- AngluarJS
- Qt for Mac苹果开发中,使用Apple Developer文档
- C++中文件读写的操作
- nginx 配置 https
- 欢迎使用CSDN-markdown编辑器
- android经典源码,仿美团外卖日历签到弹性指示器音乐播放器俄罗斯方块取色器飘落效果悬浮效果源码
- Intellij IDEA 创建Web项目并在Tomcat中部署运行
- 将字符串的首位换成大写其余小写。