---
# System prepended metadata

title: 27. Remove Element
tags: [Leetcode]

---

# 27. Remove Element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.

```
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
```

題幹給定輸入一個陣列與目標數字，希望能夠回傳不等於目標數字的元素總數，同時要求以[In-place](https://en.wikipedia.org/wiki/In-place_algorithm)處理陣列。

## 雙指針
慢指針遇到目標數字時停下，快指針找到非目標數字時停下，取代慢指針指向的元素，並向前移動一格。

```javascript
/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    let slow=0;

    for(let i=0;i<nums.length;++i){
        if(nums[i]!==val){
            nums[slow]=nums[i];
            slow++;
        }
    }
    return slow;
};
```










