-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContainsDuplicate.cpp
executable file
·71 lines (66 loc) · 1.34 KB
/
ContainsDuplicate.cpp
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
//Given an array of integers, find if the array contains any duplicates.
//Your function should return true if any value appears at least twice in the array,
//and it should return false if every element is distinct.
//solution1 time(O(n^2))
bool containsDuplicate1(int* nums, int numsSize) {
int* p = nums;
int* q = nums + numsSize - 1;
int* cursor = NULL;
bool result = true;
while (q - p>0)
{
cursor = p + 1;
while (q - cursor >= 0)
{
if (*cursor == *p)
return true;
else
{
++cursor;
}
}
++p;
}
return false;
}
//solution2 time(O(n))
bool containsDuplicate2(int* nums, int numsSize) {
bool result = true;
if (numsSize == 0)
result = false;
int hashkey[numsSize];
int hashvalue[numsSize];
for (int k = 0; k != numsSize; ++k)
hashvalue[k] = 0;
for (int i = 0; i != numsSize; ++i)
{
int id = (nums[i] + numsSize) % numsSize;
if (hashvalue[id] == 0)
{
++hashvalue[id];
hashkey[id] = nums[i];
}
else if (hashkey[id] == nums[i])
++hashvalue[id];
else
{
while (hashvalue[id] != 0)
{
id = (id + 1) % numsSize;
}
hashkey[id] = nums[i];
hashvalue[id] += 1;
}
}
for (int j = 0; j != numsSize; ++j)
{
if (hashvalue[j] >= 2)
{
result = true;
break;
}
else
result = false;
}
return result;
}