Voyz's Studio.

LeetCode算法笔记--多数元素

字数统计: 139阅读时长: 1 min
2021/01/27 Share

LeetCode算法笔记-Day65

198. House Robber

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

1
2
3
4
5
6
7
8
Example:

Input: [3,2,3]
Output: 3

Input: [2,2,1,1,1,2,2]
Output: 2

方法一:哈希表

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let n = nums.length,
hashMap = new Map();

for(let i=0;i<n;i++){
let count;
if(hashMap.has(nums[i])){
count = hashMap.get(nums[i]);
}else{
count = 0
}
if(count+1 > (n/2)) return nums[i];
hashMap.set(nums[i],count+1)
}
};
CATALOG
  1. 1. LeetCode算法笔记-Day65
    1. 1.1. 198. House Robber
    2. 1.2. 方法一:哈希表
      1. 1.2.1. Answer: