remove element

来源:互联网 发布:全军战备值班部队 知乎 编辑:程序博客网 时间:2024/06/03 05:53

参考了网上

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.

原来数组可以in-place 替换,应该成为一个子问题

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

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):        index = 0        for i in range(len(A)):            if A[i]!=elem:                A[index] = A[i]                index += 1                return index        


0 0
原创粉丝点击