---
# System prepended metadata

title: 27. Remove Element
tags: [leetcode, array]

---

# 27. Remove Element

題目：<https://leetcode.com/problems/remove-element/>

解法：採用直接解，依序找出值為val的element並移除，python使用pop(i)，c則是從後面找值非val的element取代值為val的element

Python3：

``` python 3
class Solution:
    def removeElement(self, nums: list[int], val: int) -> int:
        i = 0
        while i < len(nums):
            if nums[i] == val:
                nums.pop(i)
            else:
                i += 1
        return len(nums)

if __name__ == '__main__':
    nums = [0, 1, 2, 2, 3, 0, 4, 2]
    val = 2

    ans = Solution().removeElement(nums, val)

    print(nums)
    print(ans)
```

C：

``` c
#include <stdio.h>
#include <stdlib.h>

int removeElement(int* nums, int numsSize, int val){
    int k = numsSize - 1;
    for (int i = 0; i <= k; i++)
        if (nums[i] == val) {
            while (k > i && nums[k] == val)
                k--;
            nums[i] = nums[k];
            k--;
        }
    return ++k;
}

int main()
{
    int nums[] = {4, 5};
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    int val = 5;
    
    int ans = removeElement(nums, numsSize, val);
    
    for (int i = 0; i < numsSize; i++)
        printf("%d ", nums[i]);
    printf("\n");
    printf("%d\n", ans);
    
    return 0;
}
```

###### tags: `leetcode` `array`
