Saturday, July 4, 2015

Leetcode 27: remove element

Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
题目的意思是: 去掉array中的给定值,并返回结果array的长度。

这题如上一题不同之处在于array不是sorted的,删除给定元素,其实slow 和fast指针在做shuffle用途的时候,都可以看做是两个挡板,slow之前的element是已经处理好的,slow和fast之间的元素是不用care的,fast到size之间的元素是需要explore的。

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        //sanity check
        if (nums.size() == 0) return 0;
        //slow , fast pointer: element :[0, slow) done; [slow, fast] don't care; [fast,size]: explore
        int slow = 0;
        int fast = 0;
        while (fast < nums.size()) {
            if (nums[fast] != val) {
                nums[slow++] = nums[fast];
            }
            fast++;
        }
        return slow;
    }
};

No comments:

Post a Comment