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

leetcode Remove Duplicates from Sorted Array

时间:2015-04-21 20:20:52      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

做这个问题时没有看认真看题,把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;
}

 

leetcode Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/chaiwentao/p/4445088.html

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