8. 找出整型数组中占比超过一半的数

44 阅读1分钟
  1. 遍历数组,将数组中的元素及其出现次数存入哈希表中
  2. 遍历哈希表所有键,返回超过 数组长度一半的整数
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();

时间复杂度:

  1. 遍历数组:使用了一个 for 循环来遍历数组中的每一个元素,这一步的时间复杂度是 O(n)
  2. 哈希表操作:在遍历数组的过程中,哈希表(Map)来记录每个数字的出现次数。哈希表的插入和查找操作的平均时间复杂度是 O(1)。因此,这一步的总时间复杂度也是 O(n)
  3. 遍历哈希表:在遍历哈希表的过程中,遍历了哈希表中的所有键,在最坏情况下,k 可能等于 n,因此这一步的时间复杂度也是 O(n)

空间复杂度: 使用 Map存储数字出现的次数,最坏情况下是 n,所以空间复杂度是 O(n)