27.Remove Element

来源:互联网 发布:淘宝保税区发货 编辑:程序博客网 时间:2024/05/16 07:18

题目链接: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. * */public class RemoveElement {//112 / 112 test cases passed.//Status: Accepted//Runtime: 198 ms//Submitted: 0 minutes ago//解法一    static int removeElement(int[] A, int elem) {        int newLen = A.length;        for (int i = 0; i < newLen; i++) {        if(A[i] == elem) {        while(i < newLen && A[newLen - 1] == elem) newLen--;//找到每轮最右边的不等于elem的位置        if(i < newLen) A[i] = A[--newLen];}}    return newLen;    }        //解法二    static int removeElement2(int[] A, int elem) {        int newLen = 0;        for (int i = 0; i < A.length; i++) {        if(A[i] != elem) A[newLen ++] = A[i];}    return newLen;    }public static void main(String[] args) {System.out.println(removeElement(new int[]{1, 2, 3, 4, 5, 6, 7, 2, 2, 2}, 2));}}


0 0