题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路
思路二:如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。
在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
js代码
//方法一
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
}