Remove Duplicates from Sorted Array II--LeetCode
来源:互联网 发布:淘宝网店流量 编辑:程序博客网 时间:2024/05/20 05:25
1.题目
Remove Duplicates from Sorted Array II
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.
2.题意
在Remove Duplicates from Sorted Array 的基础上,允许每个元素重复出现两次
3.分析
1)在[2, len)范围内遍历数组
将nums[i]与nums[index - 2]作比较
若不相等,则将nums[i]放回原数组,达到去重的目的
这种解法可以拓展应用于这一类问题
2)在[1, len)范围内遍历数组
判断是否出现3个相同的数
4.代码
1)
class Solution {public: int removeDuplicates(vector<int>& nums) { int len = nums.size(); if(len <= 2) return len; int index = 2; for(int i = 2; i < len; ++i) { if(nums[i] != nums[index - 2]) { nums[index] = nums[i]; ++index; } } return index; }};
2)
class Solution {public: int removeDuplicates(vector<int>& nums) { int len = nums.size(); if(len <= 2) return len; int index = 1; for(int i = 1; i < len; ++i) { if(i < len - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1]) { continue; } nums[index] = nums[i]; ++index; } return index; }};
阅读全文
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
- Gym101194C-Mr. Panda and Strips
- Java IO File对象 获取目录内容 以及过滤器
- 《第一行代码Android》(第二版)读书笔记(二):运行时权限
- Html学习笔记7:嵌入音频和视频
- vetor操作
- Remove Duplicates from Sorted Array II--LeetCode
- [树状数组求逆序对]光荣的梦想
- SecurtCRT配置使用
- 数据库-1 给遗漏无索引的表新建索引
- MySQL/Mariadb基准测试工具-tpcc-mysql使用1
- 欢迎使用CSDN-markdown编辑器
- 南阳oj 1085 AC自动机 一般(有点坑)
- webpack3+React 的配置全解
- tablayout结合viewPager使用