[LeetCode] Single Number II

来源:互联网 发布:婚纱摄影网络销售技巧 编辑:程序博客网 时间:2024/04/30 13:19

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 mspublic 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;    }}
0 0