天天看點

[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 = <code>[3,2,2,3]</code>, val = <code>3</code>

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

題意:

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

解題:

逐一周遊數組元素,逐個比較,進行操作。

1)如果數組中元素值一緻時,隻需要将數組長度減一;否則,把cnt中下标元素指派給index的位置。因為如果中間出現給定值時,覆寫掉該位置值。