0
点赞
收藏
分享

微信扫一扫

【三分钟刷一题力扣】移除元素


原题:

​​力扣链接:27. 移除元素

题目简述:

给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

C++代码:

#include <iostream>
#include <vector>

using namespace std;

/**********************************/
//Code committed on LeetCode
class Solution {
public:
int removeElement(vector<int>& nums, int val) {

int i , j = 0;

int n = nums.size();

for(int i = 0; i < n ;i++){
if(nums[i] == val)
{
continue;
}
else
{
nums[j] = nums[i];
j++;
}
}

return j;
}
};
/**********************************/

int main() {

vector<int> tmp = {1,1,1,1,2,3};

for(int i = 0; i < tmp.size(); i++)
{
cout << tmp[i] << " ";
}

cout << endl;

Solution tSolution;

int len = tSolution.removeElement(tmp, 1);


for(int i = 0; i <len; i++)
{
cout << tmp[i] << " ";
}


return 0;
}

力扣结果展示:

【三分钟刷一题力扣】移除元素_i++


举报

相关推荐

0 条评论