[LeetCode]27. Remove Element

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

Example:
Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.


題意:

根據給定一個數組和一個關鍵值,刪除數組所有與關鍵值一樣的元素,並返回新的數組長度。


解題:

逐一遍歷數組元素,逐個比較,進行操作。

1)如果數組中元素值一致時,只需要將數組長度減一;否則,把cnt中下標元素賦值給index的位置。因爲如果中間出現給定值時,覆蓋掉該位置值。


int removeElement(int* nums, int numsSize, int val)
{
    int cnt   = 0;
    int size  = numsSize;
    int index = 0;
    for ( cnt = 0; cnt < numsSize; cnt++ )
    {
        if ( *(nums + cnt) != val )                                               {
            *(nums + index) = *(nums + cnt);
            index++;
        }
        else
        {
            size -= 1;
        }
    }
    
    if ( index != numsSize )
    {   
        *(nums + index) = '\0';
    }
    
    return size;
}


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