The sword refers to the number that appears more than half the number of times in the Offer JZ28 array (JavaScript: map)

Time limit: C/C++ 1 second, other languages ​​2 seconds Space limit: C/C++ 64M, other languages ​​128M Heat index: 661278
Knowledge points of this question: Hash array

Title description
There is a number in the array that appears more than half the length of the array. Please find out this number. For example, enter an array {1,2,3,2,2,2,5,4,2} with a length of 9. Since the number 2 appears 5 times in the array, which is more than half the length of the array, 2 is output. If it does not exist, output 0.
Example 1
Input
[1,2,3,2,2,2,5,4,2]
return value
2

Idea: Use map to store each element in traversal, add up the same elements, and then determine whether the obtained val is greater than length, greater than return key, otherwise return 0

function MoreThanHalfNum_Solution(numbers) {
    
    
    // write code here
    let len = numbers.length
    let map = new Map()
    for (let i = 0; i < len; i++) {
    
    
        let tmp = map.get(numbers[i])
        if (tmp === undefined) {
    
    
            map.set(numbers[i], 1)
        } else {
    
    
            map.set(numbers[i], ++tmp)
        }
        if (map.get(numbers[i]) > len / 2) return numbers[i]
    }
    return 0
}

Guess you like

Origin blog.csdn.net/weixin_44523860/article/details/115209616