Skip to content

Latest commit

 

History

History
88 lines (55 loc) · 1.41 KB

README_EN.md

File metadata and controls

88 lines (55 loc) · 1.41 KB

中文文档

Description

A majority element is an element that makes up more than half of the items in an array. Given a positive integers array, find the majority element. If there is no majority element, return -1. Do this in O(N) time and O(1) space.

Example 1:

Input: [1,2,5,9,5,9,5,5,5]

Output: 5

 

Example 2:

Input: [3,2]

Output: -1

 

Example 3:

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

Output: 2

Solutions

Boyer–Moore majority vote algorithm

Python3

Java

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    let candidate = 0, count = 0;
    for (let num of nums) {
        if (count == 0) candidate = num;
        if (candidate == num) {
            count++;
        } else {
            count--;
        }
    }
    let n = 0;
    for (let num of nums) {
        if (candidate == num) n++;
    }
    return n > (nums.length / 2) ? candidate : -1;
};

...