LeetCode *** 26. Remove Duplicates from Sorted Array
2016-04-05 18:52
483 查看
题目:
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 =
Your function should return length =
nums being
分析:
给定一组排序好的数组,然后返回数组中不重复元素的个数同时去掉相同的元素。
对数组进行迭代,同时判断是否有重复元素,利用一个int型的pre量来对比是否有重复元素。
代码:
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
1and
2respectively. It doesn't matter what you leave beyond the new length.
分析:
给定一组排序好的数组,然后返回数组中不重复元素的个数同时去掉相同的元素。
对数组进行迭代,同时判断是否有重复元素,利用一个int型的pre量来对比是否有重复元素。
代码:
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.empty())return 0; int length=1; int pre=nums[0]; vector<int>::iterator it=nums.begin(); it++; while(it!=nums.end()){ if(pre==*it){ it=nums.erase(it); } else{ length++; pre=*it; ++it; } } return length; } };
相关文章推荐
- 38. Count and Say | Java最短代码实现
- hdoj 3501
- 0405第四章读后感
- 错误提示: An App ID with identifier "*****" is not avaliable. Please enter a different string.
- 四则运算法则在Java中的实现
- 布局动画 LayoutAnimation
- 第6周项目2(1)画出变量占用的内存及值得变化
- 时间类 (内联成员函数)
- 第五周项目1-三角形类雏形(2)
- FragmentPagerAdapter与FragmentStatePagerAdapter区别
- android meterdesign 动画 (二)
- java中list、set、map区别(转)
- 海量数据处理
- Framework启动流程(1) - init进程启动过程
- matlab自带各种分类器的使用示例
- 单机session共享问题的解决
- git的使用 - 团队开发
- Maven教程
- 第6周项目1—IT妹子类的设计
- The 7th Zhejiang Provincial Collegiate Programming Contest