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.



從頭開始遍歷,如果碰到一個指定元素,就和末尾的一個非指定元素的位置交換。


這種類型的題目 沒太大的難度 儘量寫得簡潔並且bug free

各種循環的終止條件判斷陷阱很多



public class Solution {
    public int removeElement(int[] A, int elem) {
        int span = 1;
        for(int i=0;i<=A.length-span;i++){
            if(A[i]==elem){
                while(A[A.length-span]==elem&&A.length-span>i){
                    span++;
                }
                int temp = A[A.length-span];
                A[A.length-span]=A[i];
                A[i] = temp;
                span++;
            }
        }
        return A.length-span+1;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章