leetcode Remove Duplicates from Sorted Array

做这个问题时没有看认真看题,把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;
}
原文地址:https://www.cnblogs.com/chaiwentao/p/4445088.html