Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝卖家刷信誉平台 编辑:程序博客网 时间:2024/05/21 14:50

问题描述

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.

问题分析

根据题目,可以用一个变量count记录重复元素的个数,然后想办法将重复的元素向后移,使得前n-count位是不重复的排好序的元素,我的想法是遍历数组,如果元素等于前一个元素,就维护count的值,如果不想等,就将下标减去count的值赋值为当前的值,这样就可以把重复位变成下一个不相等的元素。

算法(C++)

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

总结

这个题的关键是将重复的元素移动到后面,而题目要求返回排好序的长度,我们可以想到用数组长度减去重复个数,这样就可以找到突破口了。

原创粉丝点击