LeetCode 27:Remove Element

来源:互联网 发布:22级战舰升级数据 编辑:程序博客网 时间:2024/06/06 09:06

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;}};




1 0
原创粉丝点击