vector 容器
来源:互联网 发布:跑步后的拉伸运动知乎 编辑:程序博客网 时间:2024/06/16 15:26
Remove Duplicates from Sorted Array
Description
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.
Translation
给出一个有序的数组,删除数组中重复的元素使得每个元素只出现以此,并且返回数组新的长度。
不能够额外定义一个数组空间,只能在原来的数组上进行操作。
Solution
class Solution {public: int removeDuplicates(vector<int>& nums) { int count = nums.size(); if (count< 2)return count; int temp = nums[0]; vector<int>::iterator iter = nums.begin(); iter++; for (; iter != nums.end();){ if (temp != (*iter)){ temp = (*iter); iter++; } else { iter=nums.erase(iter); count--; } } return count; }};
注:利用迭代器访问vector容器,并调用erase方法删除迭代器所指向的元素,返回当前迭代器指向的下一个元素。这里如果打算使用iter++或者采用另起一个变量方法,在调用erase 方法后达到保留指向的目的,会出现runtime error 的错误。
阅读全文
0 0
- vector 容器
- Vector容器
- vector容器
- Vector 容器
- vector容器
- vector容器
- 容器vector
- vector 容器
- vector 容器
- vector容器
- Vector容器
- vector容器
- vector容器
- vector容器
- vector容器
- vector容器
- vector容器
- vector 容器
- springdata && mybatis中IN关键字的传值
- JMX远程图形化监控、管理JVM
- 数据挖掘算法之离散化和二元化
- Eclipse 使用相关知识
- 异步获取json出现的小问题
- vector 容器
- sql语句执行顺序
- Hadoop课程遇到的问题集锦
- 2017计蒜之道 第四场 商汤科技的行人检测(简单)
- Redis配置文件之————redis.conf配置及说明
- Tomcat优化之内存优化
- spyder crashed during last session
- RN-API
- Pyunit源码笔记之八 testcase执行后的结果处理