27 - Remove Element

#easy
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.

Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

時間複雜度:O(n)
空間複雜度:O(1)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
            if ( nums[fastIndex] != val ) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;
    }
};

雙指針法(快慢指針法)在數組和鏈表的操作中是非常常見的,很多考察數組、鏈表、字符串等操作的面試題,都使用雙指針法。

雙指針法

雙指針法(快慢指針法): 通過一個快指針和慢指針在一個for循環下完成兩個for循環的工作。

定義快慢指針

  • 快指針:尋找新數組的元素 ,新數組就是不含有目標元素的數組
  • 慢指針:指向更新 新數組下標的位置

很多同學這道題目做的很懵,就是不理解 快慢指針究竟都是什麼含義,所以一定要明確含義,後面的思路就更容易理解了。

27.移除元素-雙指針法