Skip to content

Commit 864ff08

Browse files
committed
169. 多数元素
1 parent 49af000 commit 864ff08

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
|151|[颠倒字符串中的单词](https://leetcode.cn/problems/reverse-words-in-a-string/)|[JavaScript](./algorithms/reverse-words-in-a-string.js)|Medium|
8080
|155|[最小栈](https://leetcode.cn/problems/min-stack/)|[JavaScript](./algorithms/min-stack.js)|Easy|
8181
|160|[相交链表](https://leetcode.cn/problems/intersection-of-two-linked-lists/)|[JavaScript](./algorithms/intersection-of-two-linked-lists.js)|Easy|
82+
|169|[多数元素](https://leetcode.cn/problems/majority-element/)|[JavaScript](./algorithms/majority-element.js)|Easy|
8283
|173|[二叉搜索树迭代器](https://leetcode.cn/problems/binary-search-tree-iterator/)|[JavaScript](./algorithms/binary-search-tree-iterator.js)|Medium|
8384
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|
8485
|199|[二叉树的右视图](https://leetcode.cn/problems/binary-tree-right-side-view/)|[JavaScript](./algorithms/binary-tree-right-side-view.js)|Medium|

algorithms/majority-element.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* 169. 多数元素
3+
* @param {number[]} nums
4+
* @return {number}
5+
*/
6+
var majorityElement = function (nums) {
7+
// 哈希表
8+
// 时间复杂度: O(n)
9+
// 空间复杂度: O(n)
10+
11+
const targetNum = nums.length >> 1;
12+
const map = {};
13+
14+
for (let i = 0; i < nums.length; i++) {
15+
let curr = nums[i];
16+
map[curr] = (map[curr] || 0) + 1;
17+
if (map[curr] > targetNum) {
18+
return curr;
19+
}
20+
}
21+
};

0 commit comments

Comments
 (0)