classSolution:defsingleNumber(self, nums: List[int])->int:
length =len(nums)
res = nums[0]for i inrange(1,length):
res = res^nums[i]return res
lc 260. 只出现一次的数字 III
classSolution:defsingleNumber(self, nums: List[int])-> List[int]:
length =len(nums)
xor =0for i inrange(length):
xor ^= nums[i]# 移动如果有一位是就停了,不是全部位相等才行
mask_bit =1# 如果是0即相同就移动,一般都是按照0来判断while mask_bit & xor==0:
mask_bit = mask_bit<<1
a=0
b=0for i inrange(length):if mask_bit&nums[i]==0:
a = a^nums[i]else:
b = b^nums[i]return[a,b]
与为0只要有一位不是就不是了。
分组,一般都以0判断。
lc 268. 丢失的数字
classSolution:defmissingNumber(self, nums: List[int])->int:# 法1
adict ={k:Nonefor k inrange(len(nums)+1)}for i in nums:
adict[i]=1for k,v in adict.items():if v isNone:return k
# 法2,因为有数字没序号,所以让missing先去占一个位置
missing =len(nums)for i, num inenumerate(nums):
missing ^= i ^ num
return missing
缺失的时候直接去让序号和内容一起位运算即可
lc 338. 比特位计数
classSolution:defcountBits(self, n:int)-> List[int]:
res =[]for i inrange(n +1):
res.append(self.count(i))return res
defcount(self, num):if num ==0:return0if num %2==1:return self.count(num -1)+1return self.count(num //2)# 优化classSolution:defcountBits(self, n:int)-> List[int]:
self.memo =[0]*(n +1)
res =[]for i inrange(n +1):
res.append(self.count(i))return res
defcount(self, num):if num ==0:return0if self.memo[num]!=0:return self.memo[num]if num %2==1:
res = self.count(num -1)+1else:
res = self.count(num //2)
self.memo[num]= res
return res
要返回一个数,如果是余2等于1则继续减去一个,结果+1,否则直接对半砍掉。能被2整除只有相同位数。
lc 190. 颠倒二进制位
classSolution:defreverseBits(self, n:int)->int:
res,power =0,31while n:
res |=(n&1)<<power
power -=1
n=n>>1return res
int 是32位,要给他怼到头,与1是取最后一位和%数一样
lc 231. 2 的幂
classSolution:defisPowerOfTwo(self, n:int)->bool:return n >0and n &(n -1)==0
容易想到整个数里只有一个是1,所以减1之后相与一定是0.
lc 693. 交替位二进制数
classSolution:defhasAlternatingBits(self, n:int)->bool:
a = n^(n>>1)return a&(a+1)==0
classSolution:defisPowerOfFour(self, n:int)->bool:
mi =0while4** mi <= n:if n ==4** mi:returnTrue
mi +=1returnFalse
4的幂运算本身就够快了,别优化了。
lc 318. 最大单词长度乘积
classSolution:defmaxProduct(self, words: List[str])->int:
max_res =float('-inf')
length =len(words)
bit_list =[0]*length
for i inrange(length):for j in words[i]:
bit_list[i]|=1<<(ord(j)-ord('a'))for i inrange(length-1):for j inrange(i+1,length):if bit_list[i]&bit_list[j]==0:
max_res =max(max_res,len(words[i])*len(words[j]))if max_res ==float('-inf'):
max_res =0return max_res
# 通俗方法defpending_str(s1, s2):returnlen([x for x in s1 if x in s2])==0max=0for i inrange(len(words)-1):for j inrange(i +1,len(words)):if pending_str(words[i],words[j]):ifmax<len(words[i])*len( words[j]):max=len(words[i])*len( words[j])returnmax