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?

给定一个数组,每个元素都出现了三次,只有一个元素出现一次,要求时间复杂度为O(n),空间复杂度为O(1),找到这个元素,我们采取位运算来解决。每个整型的数都有32位,我们记录数组中所有元素每位上的和,然后与3进行模运算,这样计算完32位上的值,最后的结果就是出现一次的元素。因为出现三次的元素与三取模后肯定为0,只保留了出现一次的元素。代码如下:
public class Solution {
    public int singleNumber(int[] nums) {
        if(nums == null) return -1;
        int result = 0;
        for(int i = 0; i < 32; i++) {
            int sumBit = 0;
            for(int j = 0; j < nums.length; j++) {
                sumBit += (nums[j] >> i) & 1;
            }
            result |= (sumBit % 3) << i;
        }
        return result;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276245