2015年8月7日星期五

Lintcode: Remove Element

Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don't matter.
Have you met this question in a real interview? 
Yes
Example
Given an array [0,4,4,0,0,2,4,4]value=4
return 4 and front four elements of the array is [0,0,0,2]
Tags Expand 

Initial thoughts and solution:
Use the function erase() of vector. Note that the size of vector will keep changing.


class Solution {
public:
    /** 
     *@param A: A list of integers
     *@param elem: An integer
     *@return: The new length after remove
     */
    int removeElement(vector<int> &A, int elem) {
        for(int i = 0; i < A.size(); i++){
            if(i >= A.size()) break;
            if(A[i] == elem) {
                A.erase(A.begin()+i);
                i--;
            }
        }
        return A.size();
    }
};






Two pointers solution:
http://yucoding.blogspot.com/2013/03/leetcode-question-81-remove-element.html
One pointer iterates each element, the other pointer stores all elements which are not equal to the specified value.


class Solution {
public:
    /** 
     *@param A: A list of integers
     *@param elem: An integer
     *@return: The new length after remove
     */
    int removeElement(vector<int> &A, int elem) {
        int j = 0;
        for(int i = 0; i < A.size(); i++){
            if(A[i] != elem) A[j++] = A[i];
        }
        return j;
    }
};



没有评论:

发表评论