首页 > 其他 > 详细

Leetcode[26]-Remove Duplicates from Sorted Array

时间:2015-06-09 11:55:51      阅读:219      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!