力扣(LeetCode)试题27-移除元素 C++代码

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int removeElement(vector<int>& nums, int val) 
 9     {
10         int num = nums.size();
11         int j = 0;
12         for (int i = 0; i < num; i++)
13         {
14             if (nums[i] == val) continue;
15             else 
16             { 
17                 nums[j] = nums[i]; 
18                 j += 1;
19             }
20         }
21         return j;
22     }
23 };
24 
25 int main()
26 {
27     vector<int> nums = {3,2,2,3};
28     Solution sol;
29     int result;
30     int val = 3;
31     result = sol.removeElement(nums,val);
32     cout << result << endl;
33 
34     cout << '[';
35     for (int i = 0; i < result; i++)
36     {
37         cout << nums[i] << ' ';
38     }
39     cout << ']';
40     int p;
41     cin >> p;
42     return 0;
43 }

 

posted @ 2020-07-03 11:14  ZyLin-ux  阅读(167)  评论(0编辑  收藏  举报