[Algorithms] LeetCode 27. 移除元素
Categories Algorithms Array
Tags
来源:代码随想录
暴力解法
这边先要初始化一个size变量,原因是我们需要一直变动size的大小,不希望更改实际size之外的数组部分。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0;
int size = nums.size(); // 防止size一直变更
while (i != size) {
if (nums[i] == val) {
for (int j = i; j < size - 1; j++) {
nums[j] = nums[j + 1];
}
size--;
} else {
i++;
}
}
return size;
}
};
双指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0;
int fast = 0;
while (fast < nums.size()) {
if (nums[fast] == val) {
fast++;
} else {
nums[slow] = nums[fast];
slow++;
fast++;
}
}
return slow;
}
};
Page views: Loading... · Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号