LeetCode 之 JavaScript 解答第169題 —— 求衆數 I(Majority Element)


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


題目: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.java

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

Example 1:github

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...
數組

歡迎關注我我的公衆號:「一個不甘平凡的碼農」,記錄了本身一路自學編程的故事。
相關文章
相關標籤/搜索