剑指offer-JZ50-数组中的重复数字(C++)

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

解题思路:若数组长度不为0,则将其首元素放入unordered_set容器中;遍历数组其余元素,若在容器中没有找到该元素,则将该元素插入容器;若在容器中找到了该元素,说明该元素就是第一个重复的元素,将该元素返回

 1 #include <iostream>
 2 #include <unordered_set>
 3 
 4 using namespace std;
 5 
 6 class Solution 
 7 {
 8 public:
 9     // Parameters:
10     //        numbers:     an array of integers
11     //        length:      the length of array numbers
12     //        duplication: (Output) the duplicated number in the array number
13     // Return value:       true if the input is valid, and there are some duplications in the array number
14     //                     otherwise false
15     bool duplicate(int numbers[], int length, int* duplication) 
16     {
17         if (length>0)
18         {
19             unordered_set<int> old;
20             old.insert(numbers[0]);
21             for (int i = 1; i < length; i++)
22             {
23                 if (old.find(numbers[i]) == old.end())//如果在old序列没找到该值
24                 {
25                     old.insert(numbers[i]);//则将该值插入到old序列
26                 }
27                 else//numbers[i]元素在old序列中找到了了,则该元素便是第一个重复的元素
28                 {
29                     //将该元素返回出来
30                     *duplication = numbers[i];
31                     return true;
32                 }
33             }
34             return false;
35         }
36         else return false;
37     }
38 };
39 
40 int main()
41 {
42     Solution sol;
43     bool isnot;
44     int result[1];
45     int arr[8] = { 2, 3, 1, 0, 2, 3, 5, 3 };
46     isnot = sol.duplicate(arr, 8, result);
47     if (isnot)
48         cout << *result;
49 
50     int u;
51     cin >> u;
52     return 0;
53 }

 

posted @ 2020-07-31 12:04  ZyLin-ux  阅读(123)  评论(0编辑  收藏  举报