/
169_MajorityElement.js
66 lines (54 loc) · 1.37 KB
/
169_MajorityElement.js
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
const assert = require('assert');
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums)
{
// Check inputs:
if (nums == undefined || nums.length <= 0)
{
return undefined;
}
let hash = {};
let next_value = undefined;
// Count occurances of a number in the list of numbers:
for (let i = 0; i < nums.length; i++)
{
next_value = nums[i];
if (hash[next_value] == undefined)
{
hash[next_value] = 1;
}
else
{
hash[next_value]++;
}
}
let keys = Object.keys(hash);
let current_times_found = -Infinity;
let most_times_found = -Infinity;
let most_found_value = undefined;
keys.forEach(k => {
current_times_found = hash[k];
if (current_times_found > most_times_found)
{
most_times_found = current_times_found;
most_found_value = k;
}
});
return most_found_value;
};
describe('169_MajorityElement.js', function ()
{
it('should return 1', function ()
{
let results = majorityElement([1,1,1,2,2,3]);
assert.deepEqual(1, results);
});
it('should return 3', function ()
{
let results = majorityElement([0,0,1,1,1,1,2,3,3,3,3,3,3,3]);
assert.deepEqual(3, results);
});
});