Saturday, July 4, 2015

Leetcode 26: remove duplicates from sorted array

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.

这题属于对于sorted array的去重, 对于sorted array 去重类型的题有3类: 1. 保留一个2. 保留两个3.一个不留; 同样类似的题目有:对于一个data stream, 需要实时去掉相邻的重复的值。sorted array里面的元素可以是int, 也可以是char,对于char的array,其实就是string了。
对于sorted array去重题目,用slow, fast pointer扫描一遍array就可以达到目的。其实,sorted array 去重,相当于array shuffle的一种,移动array内的元素达到题目的目的。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        //sanity check
        if (nums.size() == 0) return 0;
        //use slow and fast pointers to deduplicate
        int slow = 0;
        int fast = 0;
        while(fast < nums.size()) {
            if (nums[fast] == nums[slow]) fast++;
            else {
                nums[++slow] = nums[fast];
            }
        }
        return slow+1;
    }
};

No comments:

Post a Comment