-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashtable.cpp
executable file
·51 lines (46 loc) · 1.03 KB
/
hashtable.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
//
//169. Majority Element
//Given an array of size n, find the majority element.The majority element is the element that appears more than ⌊ n / 2 ⌋ times.
//
//You may assume that the array is non - empty and the majority element always exist in the array
int majorityElement(int* nums, int numsSize) {
int i = 0;
int idx;
int hashKey[numsSize];
int hashvalue[numsSize];
int halfsize = numsSize / 2;
int majority;
for (int i = 0; i != numsSize; ++i)
{
hashvalue[i] = 0;
}
for (int i = 0; i != numsSize; ++i)
{
int idx = (nums[i] + 5 * numsSize) % numsSize;
if (hashvalue[idx] == 0)
{
hashKey[idx] = nums[i];
hashvalue[idx] += 1;
}
else if (nums[i] == hashKey[idx])
++hashvalue[idx];
else
{
while (hashvalue[idx] != 0)
{
idx = (idx + 1) % numsSize;
}
hashKey[idx] = nums[i];
++hashvalue[idx];
}
}
for (int i = 0; i != numsSize; ++i)
{
if (hashvalue[i]>halfsize)
{
majority = hashKey[i];
break;
}
}
return majority;
}