码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Remove Duplicates from Sorted Array II

时间:2014-09-13 22:43:46      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   2014   

 1 /*****************************************************************
 2 created:    2014/09/13 16:16
 3 filename:    remove-duplicates-from-sorted-array.cpp
 4 author:        Justme0 (http://blog.csdn.net/justme0)
 5 
 6 purpose:    有序数组中,有至少三个相同元素时删掉只留两个
 7 https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
 8 *****************************************************************/
 9 
10 #include <iostream>
11 #include <cassert>
12 #include <vector>
13 using namespace std;
14 
15 class Solution {
16 public:
17     int removeDuplicates(int A[], int n) {
18         if (n <= 2) {
19             return n;
20         }
21 
22         vector<int> iVec;
23         iVec.push_back(A[0]);
24         for (int i = 1; i < n - 1; ++i) {
25             if (!(A[i - 1] == A[i] && A[i] == A[i + 1])) {
26                 iVec.push_back(A[i]);
27             }
28         }
29         iVec.push_back(A[n - 1]);
30 
31         assert(iVec.size() <= unsigned(n));
32         for (unsigned i = 0; i < iVec.size(); ++i) {
33             A[i] = iVec[i];
34         }
35 
36         return iVec.size();
37     }
38 };
39 
40 class Solution2 {
41 public:
42     int removeDuplicates(int A[], int n) {
43         if (n <= 2) {
44             return n;
45         }
46 
47         int len = 2;
48         for (int i = 2; i < n; ++i) {
49             if (A[i] != A[len - 2]) {
50                 A[len] = A[i];
51                 ++len;
52             }
53         }
54         assert(len <= n);
55 
56         return len;
57     }
58 };
59 
60 int main(int argc, char **argv) {
61     int arr[] = {1, 1, 2, 2, 3};
62     int len = sizeof arr / sizeof *arr;
63     int new_len = Solution2().removeDuplicates(arr, len);
64     for (int i = 0; i < new_len; ++i) {
65         cout << arr[i] << endl;
66     }
67 
68     system("PAUSE");
69     return 0;
70 }

 

leetcode Remove Duplicates from Sorted Array II

标签:style   blog   http   color   io   os   ar   for   2014   

原文地址:http://www.cnblogs.com/jjtx/p/3970368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!