我具有此功能:
var majorityElement = function(nums) {
let count = {}
for(i=0; i < nums.length; i++){
let x = nums[i];
count[x] ? count[x] + 1 : count[x] = 1
}
console.log(count)
return Object.keys(count).reduce((a,b) => count[a] > count[b] ? a : b)
};
因此,我不明白为什么计数不能真正起作用,如果运行该计数,则此数组[3,3,4]
看起来像这样:
count{
3: 1
4: 1
}
不是3:2和4:1吗?
答案 0 :(得分:2)
作业应位于左侧,而不是:
count[x] ? count[x] + 1 : count[x] = 1
尝试:
count[x] = count[x] ? (count[x] + 1) : 1
var majorityElement = function(nums) {
let count = {}
for(i=0; i < nums.length; i++){
let x = nums[i];
count[x] = count[x] ? (count[x] + 1) : 1
}
console.log(count)
return Object.keys(count).reduce((a,b) => count[a] > count[b] ? a : b)
};
console.log(majorityElement([3,3,4]))