Lintcode:刪除元素

問題:

給定一個數組和一個值,在原地刪除與值相同的數字,返回新數組的長度。

元素的順序可以改變,並且對新的數組不會有影響。

樣例:

Example 1:
	Input: [], value = 0
	Output: 0


Example 2:
	Input:  [0,4,4,0,0,2,4,4], value = 4
	Output: 4
	
	Explanation: 
	the array after remove is [0,0,0,2]

python:

class Solution:
    """
    @param: A: A list of integers
    @param: elem: An integer
    @return: The new length after remove
    """
    def removeElement(self, A, elem):
        # write your code here
        lastIndex = len(A) - 1
        for i in range(lastIndex,-1,-1):
            if A[i] == elem:
                A[i], A[lastIndex] = A[lastIndex], A[i]
                lastIndex -= 1
        A = A[:lastIndex]
        return lastIndex+1

C++:

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) {
        // write your code here
        int lastIndex = A.size() - 1;
        for(int i = lastIndex; i > -1; i--)
        {
            if(elem == A[i])
            {
                int temp = A[i];
                A[i] = A[lastIndex];
                A[lastIndex] = temp;
                lastIndex--;
            }
        }
        A.resize(lastIndex+1);
        return lastIndex+1;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章