Wednesday, August 12, 2015

Leetcode: Remove Element (4ms)

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.
Hide Tags
 Array Two Pointers
Show Similar Problems






updated:
move all val to right and all non-val to the left with two pointers:
////////////////////////////////////////////////////////////
3ms
//////////////////////////////////////////////////////////
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int l=0, r=nums.size()-1;
        while(l<=r){
            while (nums[l]!=val && l<nums.size()){
                l++;
            }
            while (r>=l && r>=0 && nums[r]==val){
                r--;
            }
            if(r<l)break;
            nums[l]=nums[r];
            nums[r]=val;
            l++;
            r--;
        }
        return l;
       
       
    }
};


















Analysis:
Sweep i from left to right, and delete the target in place directly. 

/////////////////////////////////////////

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int n=nums.size();
        vector<int>::iterator it=nums.begin();
        for (int i=0;i<n;){
            if(nums[i]==val){
                nums.erase(it+i);
                --i;
                n=nums.size();//should update the size after each removing 
            }
            ++i;
        }
        return nums.size();
    }
};

No comments:

Post a Comment