码疯窝

LeetCode 每日一题 — Remove Element

2015/02/04 09:52:31    分类: 日志连载    0人评论 次浏览

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.

算法分析: 此题很简单, 就不多说.

Java:

public class Solution {
    public int removeElement(int[] A, int elem) {
        int l = A.length;
        int start = 0;
        for (int i = 0; i < l; i++) {
            if (A[i] != elem)
                A[start++] = A[i];
        }
        return start++;
    }
}

C++:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int start = 0;
        for (int i = 0; i < n; i++) {
            if (A[i] != elem) {
                A[start++] = A[i];
            }
        }
        return start;
    }
};

Python:

class Solution:
    # @param    A       a list of integers
    # @param    elem    an integer, value need to be removed
    # @return an integer
    def removeElement(self, A, elem):
        l = len(A)
        start = 0
        for i in range(0, l):
            if (A[i] != elem):
                A[start] = A[i]
                start += 1
        return start
        
继续查看有关 日志连载的文章

0个访客评论