027移除元素

 1 #include "000库函数.h"
 2 
 3 
 4 //自解1:
 5 class Solution {
 6 public:
 7     int removeElement(vector<int>& nums, int val) {
 8         if (nums.size() == 0)return 0;
 9         int j = 0;
10         for (int i = 0; i < nums.size(); ++i)
11             if (nums[i] != val)
12                 nums[j++] = nums[i];
13         return j;
14     }
15 };
16 
17 /*****************************博客解******************/
18 class Solution {
19 public:
20     int removeElement(vector<int>& nums, int val) {
21         int res = 0;
22         for (int i = 0; i < nums.size(); ++i) {
23             if (nums[i] != val) nums[res++] = nums[i];
24         }
25         return res;
26     }
27 };
28 
29 void T027() {
30     vector<int>nums = { 0,1,2,3,0,4,2 };
31     Solution s;
32     cout << s.removeElement(nums,2) << endl;
33     for (int i = 0; i < s.removeElement(nums, 2); ++i)
34         cout << nums[i] << '\t';
35     cout << endl;
36 }

 

posted @ 2019-03-14 15:21  自由之翼Az  阅读(187)  评论(0编辑  收藏  举报