Leetcode 27. Remove Element

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Remove Element

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == val) {
count++;
continue;
}
nums[i - count] = nums[i];
}
return nums.size() - count;
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != val) {
nums[count] = nums[i];
count++;
}

}
return count;
}
};

Reference

  1. https://leetcode.com/problems/remove-element/description/
如果有收获,可以请我喝杯咖啡!