当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 剑指offer50:数组中重复的数字

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

2019年08月29日  | 移动技术网IT编程  | 我要评论

银河交谊舞曲网,gai 退赛,狐剑传

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 };

参考资料

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网