1. 題意
給定一個數組,把不等于val
的元素全部移動到數組的前面來。
不需要考慮值為val
里的元素。
2. 題解
2.1 同向雙指針
我們利用雙指針,慢指針指向下一個插入的位置。而快指針不斷向前找到首個不為val
的值,找到后將快指針位置值賦給慢指針位置,慢指針右移。當快指針遍歷完整個數組時,過程結束。
class Solution {
public:int removeElement(vector<int>& nums, int val) {int l = 0;int r = 0;int n = nums.size();int cnt = 0;for (int i = 0;i < n; ++i) {if ( nums[i] != val) {nums[cnt++] = nums[i];}}return cnt;}
};
2.2 相向雙指針
由于同向雙指針有一個問題,那就是會重復賦值。比如
a=[1,2,3,4,4], val=4
, 前三個元素就會不斷自我賦值。
因此有這種相向雙指針的解法,當左邊指針指向值為val
,拿右指針指向的值賦值給左指針,右指針左移。左指針指向值不為val
就不斷右移。
重復上面的過程直到左右指針的值錯開。
class Solution {
public:int removeElement(vector<int>& nums, int val) {int l = 0;int n = nums.size(); int r = n - 1;while ( l <= r) {if ( nums[l] == val) {nums[l] = nums[r];r--;}else {l++;}}return l;}
};
3. 參考
leetcode