leetcode 80:Remove Duplicates from Sorted Array II
来源:互联网 发布:淘宝店铺装修报价单 编辑:程序博客网 时间:2024/06/03 15:34
题目:
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个我们就删除多余的,然后将后面的元素往前移动,移动操作直接借用STL的move来完成。
但是从后面开始检测,更节省时间。
实现如下:
class Solution {public:int removeDuplicates(vector<int>& nums) {int size = nums.size();if (size < 3) return size;int count = 1,flag=0;vector<int>::iterator last = nums.end();for (vector<int>::iterator i = nums.begin() + 1; i < last; ++i){while (i != last && *i == *(i - 1)){++count;++i;flag = 1;}if (count >= 3){last -= count - 2;move(i, nums.end(), i - count + 2);i -= (count - 2);count = 1;}else count = 1;if (flag == 1){flag = 0;--i;}}return (last - nums.begin());}};
下面提供更快、更简洁的方法,不需要移动数据。
记录元素个数,当第i个元素与前两个不相同时,就将该元素存到相应位置。
时间复杂度:O(n)
class Solution {public:int removeDuplicates(vector<int>& nums) {int size = nums.size();if (size < 3) return size;int rear = 1;for (int i = 2; i < size; ++i)if (!(nums[i] == nums[rear] && nums[i] == nums[rear - 1])) nums[++rear] = nums[i];return rear + 1;}};
0 0
- 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
- WordPress主题制作(9)-have_posts()和the_post()用法解析
- JDBC 基础
- WordPress 添加投稿功能
- Linux操作系统安装ActiveMQ
- Golang同步:原子操作使用
- leetcode 80:Remove Duplicates from Sorted Array II
- Maven使用大纲
- JDBC 接口
- LintCode-剑指Offer-(374)螺旋矩阵
- Android进阶之路——NDK(一)
- 欢迎使用CSDN-markdown编辑器
- C++【线程同步】-临界区同步
- unbuntu server12.04配置hadoop2.7.1(二):ubantu常用命令与准备知识
- Unity之EditorGUILayout-Enum、Popup、EnumMaskField