[LeetCode] Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

解题思路

考虑全部用二进制表示,如果我们把 第 ith 个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0). 因此取余的结果就是那个 “Single Number”。

public class Solution {
    public int singleNumber(int[] nums) {
        int cnt[] = new int[32];
        int single = 0;
        for (int i = 0; i < 32; i++) {
            for (int j = 0; j < nums.length; j++) {
                cnt[i] += (nums[j] >> i) & 0x1;
            }
            single |= cnt[i] % 3 << i;
        }

        return single;
    }
}

一种改进的做法是使用掩码变量:

  • ones 代表第 ith 位只出现一次的掩码变量
  • twos 代表第 ith 位只出现两次次的掩码变量
  • threes 代表第 ith 位只出现三次的掩码变量

当第 ith 位出现3次时,我们就 ones 和 twos 的第 ith 位设置为0。

实现代码

Java:

// Runtime: 1 ms
public class Solution {
    public int singleNumber(int[] nums) {
        int ones = 0, twos = 0, threes = 0;
        for (int i = 0; i < nums.length; i++) {
            twos |= ones & nums[i];
            ones ^= nums[i];
            threes = ones & twos;
            //对于ones 和 twos 把出现了3次的位置设置为0 
            ones &= ~threes;
            twos &= ~threes;
        }

        return ones;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值