LeetCode | 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.

//思路与11月1日的数组去重复一模一样
public class Solution {
    public int removeElement(int[] A, int elem) {
        if (A.length == 0) return 0;
        //if (A.length == 1) return A[0]==elem?0:1;    //不需要这行的额外处理
        
        int length = 0;                       //length表示满足要求的数组元素的长,逐次的取不等于elem的元素对A[length++]赋值
        for (int i=0; i<A.length; i++){
            if (A[i] != elem){                //碰到等于elem的元素什么都不做,直到后面找到不在等于elem的元素赋给A[length]
                A[length] = A[i];
                length++;
            }
        }
        return length;
    }
}

 

原文地址:https://www.cnblogs.com/dosmile/p/6444475.html