026删除排序数组中的重复项

 1 #include "000库函数.h"
 2 
 3 ////////////自解1:逐个筛选在赋值,时间最短36ms
 4 class Solution {
 5 public:
 6     int removeDuplicates(vector<int>& nums) {
 7         if (nums.size() < 2)return nums.size();
 8         vector<int>v;
 9         v.push_back(nums[0]);        
10         for (int i = 1, j = 0; i < nums.size(); ++i)
11             if (nums[i] != nums[i - 1])
12                 v.push_back(nums[i]);
13         nums = v;
14         return nums.size();        
15     }
16 };
17 
18 //////////////自解2:使用set自动去重48ms
19 class Solution {
20 public:
21     int removeDuplicates(vector<int>& nums) {
22         if (nums.size() < 2)return nums.size();
23         set<int>v;
24         v.insert(nums.begin(), nums.end());
25         nums.assign(v.begin(), v.end());
26         return nums.size();
27     }
28 };
29 
30 //////////自解3 使用算法  60ms
31 class Solution {
32 public:
33     int removeDuplicates(vector<int>& nums) {
34         return std::unique(nums.begin(), nums.end()) - nums.begin();
35     }
36 };
37 
38 ////////////博客解法1  56ms
39 class Solution {
40 public:
41     int removeDuplicates(vector<int>& nums) {
42         if (nums.empty()) return 0;
43         int pre = 0, cur = 0, n = nums.size();
44         while (cur < n) {
45             if (nums[pre] == nums[cur]) ++cur;
46             else nums[++pre] = nums[cur++];
47         }
48         return pre + 1;
49     }
50 };
51 //////////////////博客解法1  56ms
52 class Solution {
53 public:
54     int removeDuplicates(vector<int>& nums) {
55         if (nums.empty()) return 0;
56         int j = 0, n = nums.size();
57         for (int i = 0; i < n; ++i) {
58             if (nums[i] != nums[j]) nums[++j] = nums[i];
59         }
60         return j + 1;
61     }
62 };
63 
64 void T026() {
65     vector<int>nums = { 0,0,1,1,1,2,2,3,3,4 };
66     Solution S;
67     cout << S.removeDuplicates(nums) << endl;
68     for (int i = 0; i < nums.size(); ++i)
69         cout << nums[i] << '\t';
70     cout << endl;
71 }

 

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