-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindRepeatNumber.cpp
More file actions
66 lines (51 loc) · 1.33 KB
/
FindRepeatNumber.cpp
File metadata and controls
66 lines (51 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//
// Created by Wanhui on 2/12/20.
//
#include "FindRepeatNumber.h"
#include "QuadSort.h"
#include <unordered_map>
#include <iostream>
int Solution03::findRepeatNumber(std::vector<int> &nums) {
int n = 0;
int i;
// 找到数组中最大的数,
// 该步骤可省略,可将存储数组的大小设置为最大值
for (i = 0; i < nums.size(); i++) {
if (n < nums[i]) {
n = nums[i];
}
}
std::vector<int> numcount(n + 1);
for (i = 0; i < nums.size(); i++) {
numcount[nums[i]]++;
if (numcount[nums[i]] > 1) {
return nums[i];
}
}
return 0;
}
int Solution03::findRepeatNumber2(std::vector<int> &nums) {
std::unordered_map<int, int> hash(nums.size());
for (int &num : nums) {
hash[num]++;
if (hash[num] > 1) {
return num;
}
}
return 0;
}
int Solution03::findRepeatNumber3(std::vector<int> &nums) {
// using quadsort algorithm ==> sort time only O(n)
// convert std::vector<int> to int *
// just use std::vector function data()
quadsort(nums.data(), nums.size(), sizeof(int), cmp_int);
int c = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (c == nums[i]) {
return c;
} else {
c = nums[i];
}
}
return 0;
}