- 遍历数组,将数组中的元素及其出现次数存入哈希表中
- 遍历哈希表所有键,返回超过 数组长度一半的整数
function solution(array) {
// Edit your code here
// 记录最大值
const maxTarget = array.length / 2
const numMap = new Map()
for (let i = 0; i < array.length; i++) {
if (numMap.has(array[i])) {
numMap.set(array[i], numMap.get(array[i]) + 1)
} else {
numMap.set(array[i], 1)
}
}
// 遍历键拿到 出现次数超过了数字总数的一半的数字
for (const key of numMap.keys()) {
const nums = numMap.get(key)
if (nums > maxTarget) {
return key
}
}
return 0;
}
function main() {
// Add your test cases here
console.log(solution([1, 3, 8, 2, 3, 1, 3, 3, 3]) === 3);
}
main();
时间复杂度:
- 遍历数组:使用了一个
for循环来遍历数组中的每一个元素,这一步的时间复杂度是O(n)。 - 哈希表操作:在遍历数组的过程中,哈希表(
Map)来记录每个数字的出现次数。哈希表的插入和查找操作的平均时间复杂度是O(1)。因此,这一步的总时间复杂度也是O(n)。 - 遍历哈希表:在遍历哈希表的过程中,遍历了哈希表中的所有键,在最坏情况下,
k可能等于n,因此这一步的时间复杂度也是O(n)。
空间复杂度:
使用 Map存储数字出现的次数,最坏情况下是 n,所以空间复杂度是 O(n)。