---
# System prepended metadata

title: 27. Remove Element
tags: [pointer, Leetcode, python, c++, easy]

---

###### tags: `Leetcode` `easy` `pointer` `python` `c++`

# 27. Remove Element

## [題目來源:] https://leetcode.com/problems/remove-element/

## 題目:
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

* Do not allocate extra space for another array. You must do this by modifying the input array **in-place with O(1) extra memory.**

## 解題想法:
將要踢掉的數移去尾巴

## Python:
``` python=
#27. Remove Element
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        #跟尾巴交換
        head=0
        tail=len(nums)-1
        while head<=tail:
            if nums[head]!=val:
                head+=1
            else:
                nums[head],nums[tail]=nums[tail],nums[head]
                tail-=1
        return head
    
nums = [0,1,2,2,3,0,4,2]
val = 2
result=Solution()
ans=result.removeElement(nums,val)
print(nums[:ans])
```

## C++
``` cpp=
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    int removeElement(vector<int> &nums, int val)
    {
        int j = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] == val)
                continue;
            else
            {
                nums[j] = nums[i];
                j += 1;
            }
        }
        return j;
    }
};

int main()
{
    vector<int> nums = {0, 1, 2, 2, 3, 0, 4, 2};
    int val = 2;
    Solution res;
    int ans = res.removeElement(nums, val);
    cout << ans << endl;
    for (int i = 0; i < ans; i++)
    {
        cout << nums[i];
    }
    return 0;
}
```