Remove Duplicates from Sorted Array II - LeetCode 80
来源:互联网 发布:sql distinct用法 编辑:程序博客网 时间:2024/06/06 16:37
题目描述:
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.
Hide Tags Array Two Pointers
分析:双指针思想。和26题的Remove Duplicates from Sorted Array思路类似。只是此题允许最多能有2个重复的元素,因此在用双指针处理的时候,指针修改的条件要变化一下。
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.
Hide Tags Array Two Pointers
分析:双指针思想。和26题的Remove Duplicates from Sorted Array思路类似。只是此题允许最多能有2个重复的元素,因此在用双指针处理的时候,指针修改的条件要变化一下。
思路:若数组的size小于3,直接返回其size。若size大于3,那么指定前后迭代器间隔为2,循环中,首先比较两者所指元素是否相等,若相等,则直接删除后迭代器所指元素,将直接返回指向被删除元素的下一个元素的迭代器,继续循环处理。直到有迭代器指向nums.end().
以下是C++实现代码:
/*//////////20ms///*/class Solution {public: int removeDuplicates(vector<int>& nums) { int size = nums.size(); if(nums.empty()) return 0; if(size < 3) //不足3个元素,直接返回数组大小 return size; vector<int>::iterator itr1 = nums.begin(); vector<int>::iterator itr2 = itr1 + 2; //间隔为2,因为允许存在两个重复的元素 while(itr2 != nums.end()) { if(*itr1 == *itr2) //两者所指元素相等,那么直接删除右迭代器所指元素,函数返回下一个元素的迭代器 { itr2 = nums.erase(itr2); } else //若不相等,两个迭代器右移一个位置 { itr1++; itr2 ++; } } return nums.size(); //返回修改后的数组大小 }};
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
- java比较简单实用的date处理
- 网易新闻iOS版使用的18个开源组件
- 静态IP配置方法与DNS
- Spring AOP配置与应用
- C语言 FILE文件指针
- Remove Duplicates from Sorted Array II - LeetCode 80
- iOS设计模式
- Emacs安装配置
- redhat 32 or 64
- js-remove duplicate array element
- xUtils系列之BitmapUtils
- 自定义Dialog
- 关于今天jsp或servlet取不到session的问题
- MFC修改右上角图标