-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
# 169. 多数元素 | ||
|
||
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。 | ||
|
||
你可以假设数组是非空的,并且给定的数组总是存在多数元素。 | ||
|
||
示例 1: | ||
|
||
```js | ||
输入:[3,2,3] | ||
输出:3 | ||
``` | ||
|
||
示例 2: | ||
|
||
```js | ||
输入:[2,2,1,1,1,2,2] | ||
输出:2 | ||
``` | ||
进阶: | ||
尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。 | ||
来源:力扣(LeetCode) | ||
链接:https://leetcode-cn.com/problems/majority-element | ||
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 | ||
--- | ||
- 用 Map:空间复杂度不是 O(1) | ||
- 可以先排序,之后取中间的 | ||
- 摩尔投票法 | ||
```js | ||
/** | ||
* @param {number[]} nums | ||
* @return {number} | ||
*/ | ||
var majorityElement = function(nums) { | ||
let current = nums[0], count = 1 | ||
for(let i = 1; i < nums.length; i ++) { | ||
if (nums[i] === current) { | ||
count ++ | ||
} else { | ||
count -- | ||
} | ||
if (count === -1) { | ||
current = nums[i] | ||
count = 1 | ||
} | ||
} | ||
return current | ||
}; | ||
``` |