Leetcode 137 只出现一次的数字II 位计数与位变换
常规计数:
public final int singleNumber0(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if (i > 0) { if (nums[i] == nums[i - 1]) { continue; } } if (i < nums.length - 1) { if (nums[i] == nums[i + 1]) { continue; } } return nums[i]; } return nums[0]; }
位计数:
public final int singleNumber(int[] nums) { Integer re = 0; for (int i = 0; i < 32; i++) { int sum = 0; for (int num : nums) { sum += (num >> i) & 1; } re ^= (sum % 3) << i; } return re; }
位逻辑变换:
public final int singleNumber1(int[] nums) { int once = 0, thir = 0; for (int i = 0; i < nums.length; i++) { once = ~thir & (once ^ nums[i]); thir = ~once & (thir ^ nums[i]); } return once; }
位逻辑变换的真值表:
换张简单的真值表,效率低一些但好理解:
public final int singleNumber(int[] nums) { Integer X = 0, Y = 0; for (int i = 0; i < nums.length; i++) { int Z = nums[i]; X = (X & ~Y & ~Z) | (X & Y & ~Z) | (X & Y & Z) | (~X & ~Y & Z); Y = (~X & Y & ~Z) | (X & Y & ~Z) | (X & ~Y & Z); } return Y; }
当你看清人们的真相,于是你知道了,你可以忍受孤独