zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    2.1 maven配置多镜像地址
    6.4 SpringData JPA的使用
    4.3 thymeleaf模板引擎的使用
    java面试题整理
    eclipse配置运行时变量
    postman上传文件
    Python定义字符串、循环
    Charles抓包
    jmeter压测
    JMeter,postman
  • 原文地址:https://www.cnblogs.com/chaiwentao/p/4445088.html
Copyright © 2011-2022 走看看