-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path229_Majority_Element_II.js
More file actions
51 lines (47 loc) · 1.3 KB
/
229_Majority_Element_II.js
File metadata and controls
51 lines (47 loc) · 1.3 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
/*
229. Majority Element II
Given an integer array of size n, find all elements that appear more than n/3 times. The algorithm should run in linear time and in O(1) space.
*/
const expect = require('expect');
describe('229 Majority Element II', () => {
it('returns majority element', () => {
//arrange
const input = [1, 2, 1, 1, 5, 1, 2, 3, 2, 5, 1, 2, 3, 1, 1, 2, 2, 2, 3, 2, 1];
const expected = [1, 2];
//act
const actual = majorityElement(input);
//assert
expect(actual.sort()).toEqual(expected.sort());
});
it('returns majority element', () => {
//arrange
const input = [1, 2];
const expected = [1, 2];
//act
const actual = majorityElement(input);
//assert
expect(actual.sort()).toEqual(expected.sort());
});
it('returns majority element', () => {
//arrange
const input = [];
const expected = [];
//act
const actual = majorityElement(input);
//assert
expect(actual.sort()).toEqual(expected.sort());
});
});
const majorityElement = nums => {
if (nums.length < 2) return nums;
const hash = {};
const array = [];
for (const num of nums) {
if (!hash[num]) hash[num] = 1;
else {
hash[num] += 1;
}
if (hash[num] > nums.length / 3 && !array.includes(num)) array.push(parseInt(num));
}
return array;
};