设为首页 加入收藏

TOP

LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
2015-11-21 00:55:03 来源: 作者: 【 】 浏览:1
Tags:LeetCode Remove Duplicates from Sorted Array 从已排 序数 重复 元素

翻译

给定一个已排序的数组,删除重复的元素,这样每个元素只出现一次,并且返回新的数组长度。

不允许为另一个数组使用额外的空间,你必须就地以常量空间执行这个操作。

例如,
给定输入数组为 [1,1,2]

你的函数应该返回length = 2, 其前两个元素分别是1和2。它不关心你离开后的新长度。

原文

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.

代码

class Solution {
public:
    int removeDuplicates(vector
   
    & nums) { if (nums.begin() == nums.end()) return 0; vector
    
     ::iterator itor; for (itor = nums.begin(); itor != nums.end() && itor + 1 != nums.end(); ++itor) { while (*itor == *(itor + 1)) { nums.erase(itor + 1); if (itor + 1 == nums.end()) break; } } return nums.size(); } };
    
   

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[LeetCode从零单刷]Intersection .. 下一篇leetcode笔记:Decode Ways

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: