Leetcode 26. Remove Duplicates from Sorted Array
2016-05-27 22:26
549 查看
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.
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.
class Solution { public: int removeDuplicates(vector<int>& nums) { int i = 0; for (int n : nums) if (!i || n > nums[i-1]) nums[i++] = n; return i; } };
class Solution { public: int removeDuplicates(vector<int>& nums) { int n=nums.size(); if(n==0 || n==1) return n; int size=0; for(int i=1;i<n;++i){ if(nums[size] != nums[i]) nums[++size]=nums[i]; } for(vector<int>::iterator iter=nums.begin()+size+1;iter!=nums.end();) // erase(iter)后iter编程野指针,不能用iter++操作 nums.erase(iter); return nums.size(); } };
相关文章推荐
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- javascript数组操作总结和属性、方法介绍
- mysql_fetch_assoc和mysql_fetch_row的功能加起来就是mysql_fetch_array
- JavaScript Array扩展实现代码
- JavaScript:Array类型全面解析
- JavaScript之数组(Array)详解
- Javascript实现Array和String互转换的方法
- C#中Array与ArrayList用法及转换的方法
- Array栈方法和队列方法的特点说明
- Array.prototype.slice 使用扩展
- Array, Array Constructor, for in loop, typeof, instanceOf
- 实例详解ECMAScript5中新增的Array方法
- Javascript数组Array基础介绍
- js Array的用法总结
- JavaScript 判断判断某个对象是Object还是一个Array
- Javascript中的Array数组对象详谈
- js模拟实现Array的sort方法
- 在javascript将NodeList作为Array数组处理的方法
- PHP array_multisort()函数的使用札记
- PHP中array_merge和array相加的区别分析