本文共 969 字,大约阅读时间需要 3 分钟。
限制空间、时间复杂度,所以无法用Map位运算大显身手
4 ^ 1 ^ 4 ^ 6 => 1 ^ 66 对应的二进制: 1101 对应的二进制: 0011 ^ 6 二进制: 111
但是通过111无法得知是1^6
所以分组解决,奇数在一起,偶数在一起,各玩各的(异或)class Solution { public int[] singleNumbers(int[] nums) { int k = 0; for (int num : nums) { k ^= num; } int mask = 1; while ((k & mask) == 0) { mask <<= 1; } int a = 0; int b = 0; for (int num : nums) { if ((num & mask) == 0) { a ^= num; } else { b ^= num; } } return new int[] { a, b }; }}
常见位运算X&1==1 X&1==0//判断奇数偶数X>>1//整除2X<<1//乘以2X=X&(X-1)//清零最低位的1X&-X//得到最低位的1
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int res=0; while(n!=0){ ++res; n=n&(n-1);//消除最低位的1 } return res; }}
class Solution { public boolean isPowerOfTwo(int n) { if(n<=0){ return false;} return (n&(n-1))==0; }}
这两道题都用到了,消除最低位的1公式。
转载地址:http://nsnwi.baihongyu.com/