Js used to prove safety brush offer (occurrence count exceeds half of the array numbers)

Title Description

There are a number of array number that appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output.

Thinking

Thinking two: If the number has qualified a number, and it appears even more than the number of all the other numbers appear.
Save when traversing an array of two values: one is a numeric array, one number. When traversing the next number, if it is previously stored in the same figure, plus the number 1 or decremented by 1; if the number is 0, the next number is saved, and the number is set to 1. After traversing the saved numbers is also desired. And then determine whether it meets the conditions can be.

Cattle off network link

js code

//方法一
function MoreThanHalfNum_Solution(numbers)
{
    // write code here
    const len = numbers.length 
    if (len === 0) return 0
    
    const map = new Map()
    for (let i of numbers) {
        if (map.get(i) === undefined) {
            map.set(i, 1)
        }else {
            map.set(i, map.get(i)+1)
        }
    }
    for (let item of map.entries()) {
        if (item[1] > Math.floor(len/2)) return item[0]
    }
    return 0
    
}
//方法二
function MoreThanHalfNum_Solution(numbers)
{
    // write code here
    if (numbers.length === 0) return 0
    let res = numbers[0]
    let times = 1
    for (let i of numbers) {
        if (times === 0) {
            res = i
            times = 1
        }
        else if (i === res) times++
        else times--
    }
    times = 0
    for (let i of numbers) {
        if (i === res) times++
    }
    return times > Math.floor(numbers.length / 2)? res: 0
    
}

Guess you like

Origin www.cnblogs.com/dpnlp/p/yongjs-shua-jian-zhioffer-shu-zu-zhong-chu-xian-ci.html