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

26. Remove Duplicates from Sorted Array(代码思路新奇)

时间:2018-03-18 00:15:51      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:length   rem   tar   dia   memory   tps   http   cti   target   

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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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 count = 0, n = nums.size();
        for(int i = 1; i < n; i++){
            if(nums[i] == nums[i-1]) count++;
            else nums[i-count] = nums[i];
        }
        return n-count;
    }
};

 

26. Remove Duplicates from Sorted Array(代码思路新奇)

标签:length   rem   tar   dia   memory   tps   http   cti   target   

原文地址:https://www.cnblogs.com/Pretty9/p/8593587.html

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