Skip to content

Commit 5ca61ba

Browse files
author
Kohei Asai
authored
169. Majority Element (#111)
1 parent dba0c44 commit 5ca61ba

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

solutions/majorityElement.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import majorityElement from "./majorityElement";
2+
3+
describe("169. Majority Element", () => {
4+
const TEST_CASES = new Map([[[3, 2, 3], 3], [[2, 2, 1, 1, 1, 2, 2], 2]]);
5+
6+
for (const [nums, expected] of TEST_CASES) {
7+
it(`returns ${expected} when calling with [${nums}]`, () => {
8+
expect(majorityElement(nums)).toBe(expected);
9+
});
10+
}
11+
});

solutions/majorityElement.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// 169. Majority Element
2+
// https://leetcode.com/problems/majority-element/
3+
export default function majorityElement(nums: number[]): number {
4+
const counts = new Map();
5+
6+
for (const num of nums) {
7+
const count = (counts.get(num) || 0) + 1;
8+
9+
if (count >= nums.length / 2) return num;
10+
11+
counts.set(num, count);
12+
}
13+
14+
throw new Error();
15+
}

0 commit comments

Comments
 (0)