-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path51_DuplicationInArray.cpp
More file actions
111 lines (85 loc) · 1.98 KB
/
51_DuplicationInArray.cpp
File metadata and controls
111 lines (85 loc) · 1.98 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# include <iostream>
# include <cstdlib>
# include <vector>
# include <algorithm>
using namespace std;
void display_vec(vector<int> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
void display_vec(vector<string> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
bool duplicate_hash(int numbers[], int length, int* duplication)
{
vector<bool> existed(length, false);
for (int i = 0; i < length; i++)
if (existed[numbers[i]])
{
*duplication = numbers[i];
return true;
}
else
existed[numbers[i]] = true;
return false;
}
bool duplicate_place(int numbers[], int length, int* duplication)
{
if (numbers == NULL && length < 0)
return false;
int i = 0, m;
while (i < length)
{
m = numbers[i];
if (m < 0 || m > length - 1)
return false;
if (i == m) // placed well, next
i++;
else // not placed well, swap
{
if (numbers[m] == m) // duplicate
{
*duplication = m;
return true;
}
else
swap(numbers[i], numbers[m]);
}
}
return false;
}
bool duplicate(int numbers[], int length, int* duplication)
{
if (numbers == NULL && length < 0)
return false;
int i, m;
// in-place hash
for (i = 0; i < length; i++)
{
m = numbers[i] % length;
if (numbers[m] >= length)
{
*duplication = m;
return true;
}
numbers[m] += length;
}
return false;
}
int main(int argc, char *argv[])
{
int arr[] = {2, 3, 1, 0, 2, 5, 3};
int length = sizeof(arr) / sizeof(int);
int res = 0;
for (int i = 0; i < length; i++)
cout << arr[i] << ' ';
cout << endl;
if (duplicate(arr, length, &res))
cout << res << endl;
return 0;
}