天天看點

[leet code] 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.

思路與Remove Duplicates from Sorted Array 完全一緻且更加簡單(這題目用來對比的int是固定的elem).

于是仍然是兩個指針pointer是原數組指針, 無論何種情況, 每次加以; counter相當于是新數組(重用原來數組)的指針隻有數組元素與給定elem值不同的時候才加一.  最後傳回counter值作為所有與給定elem不等的數組元素數目.

public class Solution {
    public int removeElement(int[] A, int elem) {
        if(A.length == 0) return 0;
        
        int counter = 0;
        int pointer = 0;
        
        while (pointer < A.length){
            if (A[pointer] == elem)
                pointer++;
            else{
                counter++;
                A[counter-1] = A[pointer];
                pointer++;
            }
        }
        return counter;
    }
}