您的位置:首页 > 其它

LeetCode 27:Remove Element

2015-11-30 22:16 579 查看
Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

方法一:
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

//利用栈的方法
class Solution{
public:
int removeElement(vector<int>& nums, int val){
stack<int> stack1;
int n = nums.size();

if (n == 0) return 0;
for (int i = 0; i < n; i++){
if (nums[i] != val){
stack1.push(nums[i]);
}
else{
continue;
}
}
int n2 = stack1.size();
for (int j = n2-1; j >=0; j--){
nums[j] = stack1.top();
stack1.pop();
}

return n2;
}
};

int main()
{
Solution sol;
vector<int> nums1 = { 1, 2, 3,3, 4, 5 };
int n1 = sol.removeElement(nums1,3);
cout << n1 << endl;
for (int i = 0; i < n1; ++i){
cout << nums1[i] << ',';
}
system("pause");
return 0;
}


方法二:

//利用一个变量index和数组的下标i同时从数组起始位置遍历,当nums[i]!=val时,将nums[i]赋值给nums[index],
//若nums[i]=val,则不进行任何操作,跳过往后面继续遍历
class Solution{
public:
int removeElement(vector<int>& nums, int val){
int n = nums.size();
int index = 0;

for (int i = 0; i < n; ++i){
if (nums[i] != val){
nums[index++] = nums[i];
}
}
return index;
}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: