Skip to content

Commit da86363

Browse files
committed
Add solution #169
1 parent 99c3f0e commit da86363

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy|
6363
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|
6464
152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium|
65+
169|[Majority Element](./0169-majority-element.js)|Easy|
6566
179|[Largest Number](./0179-largest-number.js)|Medium|
6667
191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy|
6768
203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy|

solutions/0169-majority-element.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* 169. Majority Element
3+
* https://leetcode.com/problems/majority-element/
4+
* Difficulty: Easy
5+
*
6+
* Given an array nums of size n, return the majority element.
7+
*
8+
* The majority element is the element that appears more than ⌊n / 2⌋ times.
9+
* You may assume that the majority element always exists in the array.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums
14+
* @return {number}
15+
*/
16+
var majorityElement = function(nums) {
17+
const map = new Map();
18+
nums.forEach(n => map.set(n, (map.get(n) || 0) + 1));
19+
20+
const sorted = [...map].sort(([,a], [,b]) => b - a);
21+
return sorted[0][0];
22+
};

0 commit comments

Comments
 (0)