LeetCode 126 Remove Element

来源:互联网 发布:防身甩棍淘宝网 编辑:程序博客网 时间:2024/05/05 09:00
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.

分析:

每次碰到相等的,就把当前最后一个放到当前位置,同时长度减1,继续检查此位置,直到不相等

public class Solution {    public int removeElement(int[] A, int elem) {                if(A == null || A.length == 0)            return 0;                int i=0;        int len = A.length;        while(i < len){            if(A[i] == elem){                A[i] = A[len-1];                len--;                continue;            }            i++;        }        A = Arrays.copyOf(A, len);        return A.length;    }}


0 0
原创粉丝点击