LeetCode - Remove Element

来源:互联网 发布:eai是什么软件 编辑:程序博客网 时间:2024/05/16 17:47

https://leetcode.com/problems/remove-element/

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.

这道题就是遍历一遍,维持一个指针,指针前面的位置都不是elem,如果碰到不是elem的值,就把这个值复制到指针所在位置,指针前移,如果碰到elem,就不复制,继续遍历数组。代码如下:

    public int removeElement(int[] A, int elem) {        if(A==null || A.length==0) return 0;        int current = 0;        for(int i=0; i<A.length; i++){            if(A[i]==elem) continue;            else{                A[current] = A[i];                current++;            }        }        return current;    }

时间复杂度O(n),空间复杂度O(1)

0 0
原创粉丝点击