Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.Do not allocate extra space for another array, you must do this in place with constant memory.The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

思路:
變量i,j分別指向數組的首部和尾部,變量k存儲數組中有多少與val相同的元素。不斷循環將數組尾部的非val的數組元素賦值給數組首部的nums[i](nums[i] = val)。用k記錄數組中val的個數,返回numsSie - k。

代碼:

int removeElement(int* nums, int numsSize, int val) {
    int i = 0, j = numsSize - 1, k = 0;

    while(i <= j)
    {
        while(j >= i && nums[j] == val)
        {
            j--;
            k++;
        }

        if(i <= j && nums[i] == val)
        {
            nums[i] = nums[j];
            j--;
            k++;
        }
        i++;
    }
    return numsSize - k;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章