Single Number II

来源:互联网 发布:mba与emba的区别 知乎 编辑:程序博客网 时间:2024/06/05 08:43

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?


思路:

这个解法是我看到最好的,最容易懂的解法。

Idea: if we look all the last bit of the numbers (assuming all are 32-bit) in the array, there must be 3k+1 or 3k `1's in total depending whether the single number's last bit is one or zero. This observation holds for all the rest 31 bits as well. Hence, if we sum all the numbers only at certain bit and mod by 3, we can get the corresponding bit the single number. Do this for all 32-bit, we can get all bits of that number. This generalizes the solution of LeetCode: Single Number I, where xor all the numbers is essentially trying to add all bits and then mod by 2...

就是 Int 32位,因为每个数字appear 3次,所以,每个位要么为3K+1,或者为3K.

取决于只出现一次的位是0,还是1.

这样思路就是取每一位相加,然后%3, 这样下来就是那个出现1次的数的位数,然后移动回去,加起来就是出现一次的数。

public class Solution {     public int singleNumber(int[] A) {         int single = 0;         for(int i=0; i<32; i++){             int bit = 0;             for(int j=0; j<A.length; j++){                 bit += (A[j]>>i & 1);             }             bit = bit%3;             single += bit<<i;          }         return single;     } }


0 0
原创粉丝点击