• 剑指offer50:数组中重复的数字


    1 题目描述

      在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

    2 思路和方法

      map的find函数:

        map底层是红黑树实现的,因此它的find函数时间复杂度:O(logn)

        而unordered_map底层是哈希表,因此它的find函数时间复杂度:O(l)

        而algorithm里的find函数是顺序查找,复杂度为O(n)

      find函数:【https://blog.csdn.net/u012604810/article/details/79798082】

      (不懂)iterator find ( const key_type& key );如果key存在,则find返回key对应的迭代器,如果key不存在,则find返回unordered_map::end。因此可以通过map.find(key) == map.end()来判断,key是否存在于当前的unordered_map中。 

    3 C++核心代码

     1 class Solution {
     2 public:
     3     // Parameters:
     4     //        numbers:     an array of integers
     5     //        length:      the length of array numbers
     6     //        duplication: (Output) the duplicated number in the array number
     7     // Return value:       true if the input is valid, and there are some duplications in the array number
     8     //                     otherwise false
     9     bool duplicate(int numbers[], int length, int* duplication) {
    10                if (!numbers || length <= 1)
    11             return false;
    12         unordered_map<int,int> umap;
    13         for (int i = 0; i < length; ++i) {
    14             umap[numbers[i]]++;
    15             if (umap[numbers[i]]>1){
    16                 *duplication = numbers[i];
    17                 return true;
    18             }
    19         }
    20         return false;
    21     }
    22 };
    View Code

    参考资料

    https://blog.csdn.net/zjwreal/article/details/89053795(find函数不懂)

  • 相关阅读:
    数据库连接池大小
    java的关闭钩子(Shutdown Hook)
    为线程池中的每个线程设置UncaughtExceptionHandler
    java 线程的interrupt和sleep、wait
    中断
    NIO
    VMware 安装 VMware Tools 工具
    php 雪花算法
    python 执行系统文件
    php curl 获取响应头
  • 原文地址:https://www.cnblogs.com/wxwhnu/p/11425712.html
Copyright © 2020-2023  润新知