题目地址:https://leetcode-cn.com/problems/remove-element/
题目描述:给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
代码参考:
#include <iostream>
#include <vector>
using namespace::std;
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];
}
}
return slowIndex;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
vector<int> numberAry = {1,2,3,4,5};
int lenth = Solution().removeElement(numberAry, 3);
return 0;
}










网友评论