LeetCode 之 JavaScript 解答第169题 —— 求众数 I(Majority Element)

Time:2019/4/4
Title: Majority Element 1
Difficulty: easy
Author: 小鹿

问题:Majority Element 1

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

solve:

▉ 算法思绪:摩尔投票算法

问题的要求是让我们求数组中凌驾一半数据以上雷同的元素且老是存在的。有如许一个思绪要和人人分享:

假如有如许一种数据,数组中的所存在的这个凌驾 n/2 以上的数据(众数)一定比与此众数不雷同的其他元素个数要多(n/2 以上)。我们能够如许统计,用一个变量来计数,另一个变量纪录计数的该元素,遍历全部数组,假如碰到雷同的 count 加 +1,差别的就 -1 ,末了所存储的就是众数,由于其他数据的个数比众数个数要少嘛,这就是所谓的摩尔投票算法

▉ 代码完成:
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    //用来计数雷同的数据
    let count = 0;
    //存储当前的元素
    let majority = 0;
    //遍历全部数组
    for(let i = 0;i < nums.length; ++i){
        //假如 count 为 0 
        if(count === 0){
            //将当前数据为众数
            majority = nums[i];
            count++;
        }else if(majority === nums[i]){
            //假如遍历的当前数据与存储的当前数据雷同,计数+1
            count++;
        }else{
            //若不雷同,计数 - 1
            count--;
        }
    }
     //假定雷同的众数呢?
    if(count === 0){
        return -1;
    }else{
        return majority;
    }
};

迎接一同加入到 LeetCode 开源 Github 堆栈,能够向 me 提交您其他言语的代码。在堆栈上对峙和小伙伴们一同打卡,配合完美我们的开源小堆栈!
Github:https://github.com/luxiangqia…

迎接关注我个人民众号:「一个不甘寻常的码农」,纪录了本身一起自学编程的故事。

    原文作者:小鹿
    原文地址: https://segmentfault.com/a/1190000018772634
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞