红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

做这个问题时没有看认真看题,把sorted看漏了,结果写了如下代码:虽然错了,但我觉得我下面这个代码写的还是挺不错的。

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int removeDuplicates(int A[], int n) {
 6     int t = 0;
 7     for (int i = 0; i < n; i++){
 8         A[i - t] = A[i];
 9         for (int j = 0; j < i-t; j++){
10             if (A[i] == A[j]){
11                 t++;
12                 break;
13             }
14         }
15     }
16     return n - t;
17 }
18 
19 int main(){
20     int A[] = {2, 2, 3, 4, 2, 5, 6, 3};
21     int n = removeDuplicates(A, 8);
22     for (int i = 0; i < n; i++){
23         cout << A[i] << endl;
24     }
25     cout << "n = " << n << endl;
26 }

改正后:

 

#include<iostream>

using namespace std;

int removeDuplicates(int A[], int n) {
    int t = 0;
    for (int i = 1; i < n; i++){
        A[i - t] = A[i];
        if (A[i-t] == A[i - t-1]){
            t++;
        }
    }
    return n - t;
}

int main(){
    int A[] = {2, 2, 3, 4, 4,5, 6, 6};
    int n = removeDuplicates(A, 8);
    for (int i = 0; i < n; i++){
        cout << A[i] << endl;
    }
    cout << "n = " << n << endl;
}

 

posted on 2015-04-21 18:03  红桃J  阅读(125)  评论(0编辑  收藏  举报