Lintcode:删除元素

版权声明:本文未经博主允许不得转载。 https://blog.csdn.net/pianzang5201/article/details/90581887

问题:

给定一个数组和一个值,在原地删除与值相同的数字,返回新数组的长度。

元素的顺序可以改变,并且对新的数组不会有影响。

样例:

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;
    }
};

猜你喜欢

转载自blog.csdn.net/pianzang5201/article/details/90581887