设计逻辑运算,真值表达式为:
public final int singleNumber0(int[] nums) { int x = 0, y = 0; for (int i = 0; i < nums.length; i++) { int z = nums[i]; x = (x & ~y & ~z) | (z & (x ^ y)); y = (~x & (y ^ z)) | (x & ~y & z); } return y; }
更简便的解法为直接异或,因为只需要排除出现两次的元素:
public final int singleNumber(int[] nums) { int re = 0; for (int i = 0; i < nums.length; i++) { re ^= nums[i]; } return re; }
JS 自定义逻辑运算:
var singleNumber = function(nums) { let x,y = 0; for(let i=0;i<nums.length;i++){ let z = nums[i]; x=(x&~y&~z)|(~x&y&z)|(x&~y&z); y=(~x&y&~z)|(~x&~y&z)|(x&~y&z); } return y; };
JS 按位异或:
var singleNumber = function(nums) { let re = 0; for(let i=0;i<nums.length;i++){ re^=nums[i]; } return re; };