0
点赞
收藏
分享

微信扫一扫

剑指 Offer 56 - II. 数组中数字出现的次数 II(javascript)

回溯 2022-04-08 阅读 72

一、题目地址

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/comments/

二、具体代码

/**
 * @param {number[]} nums
 * @return {number}
 */
// 位运算,通用模版
// 时间复杂度:O(N)
// 空间复杂度:O(1)
 var singleNumber = function(nums) {
    //  正确做法,需要加上每一位填充0的细节
    let counts = new Array(32).fill(0);
    /* 
        错误做法,理由见打印结果:
        let counts = new Array(32);
        console.log(counts[1]);//undefind
     */
    for(let num of nums) {
        for(let j=0; j<32; j++) {
            counts[j] += (num & 1);
            num >>>= 1;
        }
    }
    let res = 0, m = 3;
    for(let i=0; i<32; i++) {
        res <<= 1;
        res |= (counts[31-i] % m);
    }
    return res;
};

三、补充链接

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/solution/mian-shi-ti-56-ii-shu-zu-zhong-shu-zi-chu-xian-d-4/

举报

相关推荐

0 条评论