Skip to content

Latest commit

 

History

History
68 lines (53 loc) · 1.54 KB

169.Majority Element.md

File metadata and controls

68 lines (53 loc) · 1.54 KB

169. Majority Element

Easy

https://leetcode.com/problems/majority-element/description/

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.

Example 1:

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

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    // 解法二:投票法(假如没有题干的约束“majority 的出现次数大于2/N”,投票算法就失败了,就用解题一里的暴力解法吧)
    let count = 1;
    let majority = nums[0];
    for(let i = 1; i < nums.length; i++) {
        if(count == 0) {
            majority = nums[i];
        }
        if (nums[i] === majority) {
            count ++;
        } else {
            count --;
        }
        return majority;
    }
    
    
    // 解法一:暴力解法,map 存储每个数字以及出现的次数,最后遍历 map 找出最大数
    const map = new Map()
    for (let i = 0; i < nums.length; i += 1) {
        const element = nums[i]
        const count = map.get(element)
        map.set(element, count !== undefined ? count + 1 : 1)
    }
    let [majoritKey, majoritCount] = [0, 0]
    let  = undefined
    for (let [key, value] of map) {
      if(value > majoritCount) {
          [majoritKey, majoritCount] = [key, value]
      }
    }
    return majoritKey
};