[leetcode Q26] Remove Duplicates from Sorted Array
来源:互联网 发布:windows邮件客户端 编辑:程序博客网 时间:2024/05/22 18:22
1. 题目要求
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
不另外申请空间,返回新的数组长度,在原数组中超过新长度的元素可以是任意的。
2. 思路&注意
思路很简单,遍历一遍数组,检查前一个元素与当前元素是否相同,相同则删除当前元素。
- 检查输出值
vector erase
函数返回的是指向待删除元素下一个元素的迭代器
3. 实现
class Solution {public: int removeDuplicates(vector<int>& nums) { if(nums.size() == 0 || nums.size() == 1) return nums.size(); vector<int>::iterator i; vector<int>::iterator j; for( i = nums.begin() + 1; i < nums.end(); ) { j = i - 1; if(*j == *i) i = nums.erase(i); else i++; } return nums.size(); }};
测试 AC
0 0
- [leetcode Q26] Remove Duplicates from Sorted Array
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array
- [HNOI2008] [BZOJ1009] GT考试
- 第六章:Linux的文件权限
- NDK开发环境的搭建
- 智能硬件X1000平台代码下载编译方法
- ytu 2228 判断链表
- [leetcode Q26] Remove Duplicates from Sorted Array
- 2015年10月最新大神班小码哥视频
- jsp编译、执行过程
- 2015年10月最新大神班小码哥视频
- hbase源码打包
- 最新大神班小码哥视频
- Android ContentProvider和Uri详解
- centos的nginx+https配置
- 理解c语言指针很关键的几句话,二维数组与指针类型的分析