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?
考察一个数的二进制表示。将一个数表示成二进制会发现其每一位0不是就是1.题目描述说除了有一个数只出现了1次之外,其余的数都出现了3次。因此我们可以统计在二进制的每一位上0和1出现的次数,将次数mod3 则其结果就是single number 二进制表示时在这一位上的结果。
1 public class Solution { 2 public int singleNumber(int[] nums) { 3 int ans = 0; 4 for (int i = 0; i < 32; i++) { 5 int count = 0; 6 for (int j = 0; j < nums.length; j++) { 7 count += (nums[j] >> i) & 1; 8 } 9 if (count % 3 != 0) { 10 ans |= 1 << i; 11 } 12 } 13 return ans; 14 } 15 }

浙公网安备 33010602011771号