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.

solution: use two pointer, start and end pointer, exchange the found value in start with value in end. 

class Solution {
public:
    int removeElement(vector& nums, int val) {
        if(nums.size() == 0)
            return 0;
        int start = 0; 
        int end = nums.size()-1;
        while(start <= end)
        {
            while(end >= 0 && nums[end] == val)
                end--;
            if(end <= start)
                return end + 1;
            while(start < nums.size() && nums[start] != val)
                start++;
            if(end <= start)
                return start;
            if(nums[start] == val){
                //swap.
                int tmp = nums[start];
                nums[start] = nums[end];
                nums[end] = tmp;
                start++;
                end--;
            }
            
        }
        return start;
    }
};


你可能感兴趣的:(leetcode)