LeetCode题解–137. Single Number II

链接

LeetCode题目:https://leetcode.com/problems/single-number-ii/

难度:Medium

题目

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题目大意是一个数组中只有一个数字出现一次,其余的数字都出现了三次,在线性时间内找出那个单独的数字。

分析

最简单的想法是用map,遍历一次数组将出现三次的数字删掉,最后剩下的数字就是所求的,但是空间复杂度是O(n)。
更好的做法是用一个长度为32的bits数组统计每个数字每一位中1出现的次数,线性扫描一遍数组后,对bits数组的每一位进行模3,这样就能知道单独的数字每一位是0或1,时间复杂度和用map的做法都是O(n),因为bit数组大小固定所以空间复杂度降低到了O(1)。

代码

class Solution {
public:
    int singleNumber(vector<int> &nums) {
        int bits[32] = {0};
        for (auto num:nums) {
            for (int i = 0; i < 32; i++) {
                bits[i] += (num >> i) & 1;
            }
        }
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            bits[i] %= 3;
            ans += bits[i] << i;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值