题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param numbers int整型一维数组 * @return int整型 */ function MoreThanHalfNum_Solution(numbers) { // write code here let map = new Map(); for (let i = 0; i < numbers.length; i++) { if (map.has(numbers[i])) { //map.get(numbers[i]) + 1不能直接这样写,必须要用set形式 map.set(numbers[i],map.get(numbers[i]) + 1) } else { map.set(numbers[i], 1); } } //console.log(map.values()) let res = Math.floor(numbers.length / 2) + 1; for (let item of map) { if (Number(item[1]) >= res) { return item[0]; } } } module.exports = { MoreThanHalfNum_Solution: MoreThanHalfNum_Solution, };