LeetCode日本語修行6日目- [27- 指定要素の削除]


Remove Element

参考:https://leetcode.com/problems/remove-element/

問題の内容:

配列numsの中に、valとイコールのvalueをその場で削除し、新しい長さを返します。
余分なスペースを使わない。順序は変更可能です。新しい長さの先に気にしない。

例:

例1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.

例2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]

ヒント:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100


二重ポインタを使います、

class Solution {
    fun removeElement(nums: IntArray, `val`: Int): Int {
        var start = 0
        var end = nums.size - 1

        while(start <= end){
            if(nums[start] == `val`){
                nums[start] = nums[end]
                end--
            } else {
                start++
            }
        }

        return start
    }
}