码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[26]-Remove Duplicates from Sorted Array

时间:2015-06-09 11:58:43      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:new   remove   for   extra   sorted   

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.


思路:需要额外添加一个新的变量pos,初始值为0,用来记录非重复元素的位置。从数组的第二个元素开始遍历,如果和前面的元素相等,则直接跳到下一个;如果不等,则将该数组的值赋值给++pos位,接着继续遍历下一个;

Code(c++):

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return 0;
        int pos = 0,i = 1;
        while(i < n){
            if(nums[i] == nums[i-1]){
                i++;
            }else{
                nums[++pos] = nums[i++];
            }
        }
        n = pos+1;
        nums.resize(n);
        return n;
    }
};

Leetcode[26]-Remove Duplicates from Sorted Array

标签:new   remove   for   extra   sorted   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46423281

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!