zoukankan      html  css  js  c++  java
  • 剑指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函数不懂)

  • 相关阅读:
    git
    node cheerio
    Git是目前世界上最先进的分布式版本控制系统
    精华 ionic入门之色彩、图标、边距和界面组件:列表
    如何将腾讯视频的qlv格式转换为mp4格式
    php无限级分类实战——评论及回复功能
    Yii2 前后台登陆退出分离、登陆验证
    linux 更改文件所属用户及用户组
    wdcp 开启某个Mysql数据库远程访问
    Rem实现自适应初体验
  • 原文地址:https://www.cnblogs.com/wxwhnu/p/11425712.html
Copyright © 2011-2022 走看看