zoukankan      html  css  js  c++  java
  • 数组中重复的数字

    在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。

    也不知道每个数字重复几次。请找出数组中任意一个重复的数字。

    例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

    思路:用一个辅助数组,数组大小为n,遍历数组将数组的值作为辅助数组的下标

    辅助数组的值统计,统计过程中,如果不等于一,就输出

    (这里要注意的是一位数组初始化,并且全部赋值为0)

    时间复杂度O(n),空间复杂度不是O(1)

    代码:

    // 思路 对数组进行遍历,将数组的值作为另一个数组得下标,
    //该下标对应的值加1,并赋值给一个变量
    //当这个变量的值大于1时就是要的结果
    class Solution {
    public:
    
        bool duplicate(int numbers[], int length, int* duplication) {
    
            if (length <= 0 || numbers == NULL)
                return false;
    //       int arr2[length+1];
    //       for(int i = 0; i < length+1; i++)
    //            arr2[i] = 0;
           int *arr2 = (int *)calloc(length, sizeof(int));
           int temp = 0;
           for(int i = 0; i < length; i++)
           {
               arr2[numbers[i]]++;
               temp = arr2[numbers[i]];
               if (temp > 1)
               {
                   *duplication = numbers[i];
                   break;
               }
           }
           if (temp > 1)
            return true;
           else
            return false;
        }
    };
  • 相关阅读:
    makefile 中 $@ $^ %< 使用
    makefile中的自动化变量$@,$%,$
    linux grep命令
    wc命令
    linux下echo命令
    winscp和putty提取固件教程
    WinSCP和PuTTY在刷openwrt固件的使用教程
    OPENWRT学习笔记入门篇
    第五章 并发性:互斥和同步
    getCurrentSession()和getOpenSession()的区别
  • 原文地址:https://www.cnblogs.com/xiaokang01/p/12455214.html
Copyright © 2011-2022 走看看