您的位置:首页 > 其它

Leetcode 位运算知识点总结

2018-03-05 11:05 381 查看
一个颇有好感的爱豆今天入伍了,人品和才华都没的说,但是因为这样或那样的原因,最终不得已提前进了部队,挺心疼他的。明年年底见吧。

昨天刷B站,看到国内一个练习生选秀节目中舞蹈导师批评国内练习生各种借口各种不努力,不禁感慨国内娱乐圈来钱太容易了。韩国爱豆生存压力大,每年出道的团很多,但是最后活下来的就那么几个。所以为了成功,他们需要不断努力不停练习,最终的表现和国内高下立判。

环境是很大的一个方面,类比于特征工程,是人(模型)表现出来的上限。

最近听闻谁谁谁要去读博了,谁谁谁准备把工作辞职了去读研还是蛮感慨的,原先认为找到一份好工作安逸地过一生就好,现在发现并不是如此。可能人要离开舒适圈才能更好地打磨自己的人生吧。

一辈子说长也长,说短也就那么一瞬。就活到哪算哪,活到啥时候算啥时候吧。

来看下Leetcode中Tag为Bit Manipulation的题目

注:187. Repeated DNA Sequences

这题用位操作的方式太诡异了,我还是倾向于用hash table来完成,所以没有列入答案。

756. Pyramid Transition Matrix

在Solutions里暂时没有发现位操作的解答,自己也没有想到合适的解法,暂时保留。

[Leetcode190] Reverse Bits:将数的二进制表示转置, Easy

[Leetcode 231] Power of Two:判断一个数是否是2的指数,Easy

思路:判断 n & (n-1) = 0

[Leetcode 342] Power of Four:判断一个数是否是4的指数,Easy

[Leetcode 191] Number of 1 Bits:统计数n二进制表示中1的个数,Easy

class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count=0
while(n):
n = n&(n-1)
count = count +1
return count


[Leetcode 338] Counting Bits:返回一个数组,统计从0到n中每个数二进制表示1的个数,Medium

思路 ret[i] = ret[i&(i-1)]+1

[Leetcode 461] Hamming Distance:计算两个数的汉明距离,Easy

思路:两个数a,b的汉明距离为 a^b 中1的个数

[Leetcode 477] Total Hamming Distance:计算一个数组中两个数汉明距离的总和,Medium

思路:∑ione(i)zero(i)∑ione(i)zero(i),ii为第几个bit位

思路:利用0^a = a, a^a = 0的性质

[Leetcode 389]Find the Difference:找出s和t中唯一不同的小写字母,Easy

思路:拼接s和t

[Leetcode 268] Missing Number:判断长度为n的数组中缺少[0,…,n]中的数,Easy

[Leetcode 136] Single Number:一个数组中所有的数都是成对出现的,除了一个数,找出这个数,Easy

[Leetcode 260] Single Number III:一个数组中所有的数都是成对出现的,除了两个数,找出这两个数,Medium

思路:两个不相等的元素在位级表示上必定会有一位存在不同,

将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果,

据异或的结果1所在的最低位,把数字分成两半,每一半里都还有一个出现一次的数据和其他成对出现的数据, flag = result & (~(result-1))

问题就转化为了两个独立的子问题“数组中只有一个数出现一次,其他数都出现了2次,找出这个数字”。

[Leetcode 137] Single Number II:一个数组中所有的数都出现了三次,除了一个数,找出这个数,Medium

思路:考虑每个元素的为一个32位的二进制数,这样每一位上出现要么为1 ,要么为0。对数组,统计每一位上1 出现的次数count,必定是3N或者3N+1 次。让count对3取模,能够获得到那个只出现1次的元素该位是0还是1。

(Python深坑,没有无符号移动,这题没有给数据范围推测应该是−231−231到231−1231−1,但是有个用例为231231就wa下去了,实际上数组开32个就可以了,要先变负为正,然后记录负数的个数再处理)

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
bitArrays = [0]*33
for num in nums:
i,flag = 0,1
if num<0:
num = -num
bitArrays[32]+=1
while(i<32):
if num & flag: bitArrays[i]+=1
flag = flag<<1
i+=1
i, ret,flag = 0,0, 1
while(i<32):
if bitArrays[i]%3: ret+=flag
flag=flag<<1
i+=1
if bitArrays[32]%3: ret = -ret
return ret


[Leetcode 169] Majority Element:有个数在数组中出现了至少n/2次,求该数,Easy

思路:开一个长度为32的数组,统计每个数组中1的个数

[Leetcode 371] Sum of Two Integers:不用加减法实现两数之和,Easy

思路:加法是异或,进位是与<<1,Python需要越界检查

# -*- coding:utf-8 -*-
class Solution:
def Add(self, a, b):
while(b):
a,b = (a^b) & 0xFFFFFFFF,((a&b)<<1) & 0xFFFFFFFF
return a if a<=0x7FFFFFFF else ~(a^0xFFFFFFFF)


[Leetcode 401] Binary Watch:4个LED灯表示小时,6个LED灯表示分钟,求能够表达的所有时间,Easy

class Solution(object):
def readBinaryWatch(self,num):
ret=[]
for h in range(12):
for m in range(60):
if bin(h).count('1')+bin(m).count('1') == num:
if m<10:
ret.append(str(h)+':'+'0'+str(m))
else:
ret.append(str(h)+':'+str(m))
return ret


[Leetcode 405] Convert a Number to Hexadecimal:将一个整数转化为16进制表示,Easy

思考:注意负数的二进制表示为其正数的反码+1

[Leetcode 476] Number Complement:求某个数的补码形式,Easy

class Solution(object):
def findComplement(self,num):
'''
:param num:  int
:return:  int
'''
tmp = num
ans = 1
while(num):
ans = ans*2
num = num >>1
return (ans-1) ^ tmp


[Leetcode 693] Binary Number with Alternating Bits:判断一个数的二进制表示是否01是交错出现,Easy

思路:如果一个数满足要求,那么

num = 101 ^ 1010 = 1111

最后判断 num & (num+1) 是否为0即可

[Leetcode 762] Prime Number of Set Bits in Binary Representation

class Solution(object):
def __init__(self):
MAXN = 1000
self.prime = [1]*(MAXN+1)
self.prime[0]=self.prime[1]=0
for i in range(2,MAXN+1):
if self.prime[i]==1:
for y in range(i*i,MAXN+1,i):
self.prime[y]=0

def countPrimeSetBits(self, L, R):
"""
:type L:
:type R:
:rtype:
"""
ans = 0
for x in range(L, R + 1):
ans += self.prime[bin(x).count('1')]
return ans


[Leetcode 318] Maximum Product of Word Lengths:给定一个字符串数组words,寻找length(words[i]) * length(words[j])的最大值,其中两个单词不包含相同字母。你可以假设每一个单词只包含小写字母。如果不存在这样的两个单词,返回0。Medium

思路:把单词映射到长度为26bit的数上进行计算

[Leetcode 78] Subsets 求集合的所有子集,Medium

思路:子集的个数有2n2n种,000,001,010,011,100,101,110,111

[Leetcode 784] Letter Case Permutation:输出字符串中为英文字母的所有大小写组合,Easy

[Leetcode 201] Bitwise AND of Numbers Range, [m, n]范围的按位与结果,Medium

思路:只有m和n的bit位的长度一样时候才有值,其他都要返回0

[m, n]范围的按位与的结果最终转化为m与n的公共“左边首部(left header)”

class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
count=0
while(m!=n):
m=m>>1
n=n>>1
count=count+1
return m<<count


[Leetcode 393] UTF-8 Validation:判断UTF8编码的正确性,Medium

一个UTF8字符的长度从1到4个字节不等,服从下列规则:

对于1字节的字符,首位数是0,后面是unicode代码。

对于n字节的字符,前n位数全是1,第n+1位是0,后面跟着n-1个字节,最高位的两位数是10。

思考:一个典型的模拟题

class Solution(object):
def validUtf8(self, data):
count =0
#print '{:b}'.format(data[0])
for d in data:
if count==0:
if d>>3 == 0b11110:
count = 3
elif d>>4 == 0b1110:
count =2
elif d>>5 == 0b110:
count =1
elif d <128:
pass
else:
return False
else:
if (d>>6)!=0b10:
return False
count = count -1
return count == 0


[Leetcode 397] Integer Replacement:如果一个数是偶数,做除2操作,否则加1或减1,求该数到1所需操作次数的最小值。Medium

思路:奇数的话尾数有01和11两种情况,前者-1后者+1(注意到3要单独讨论)

class Solution(object):
def integerReplacement(self,num):
'''
:param num:
:return:
'''
cnt = 0
while(num!=1):
if num & 1 == 0:
num = num>>1
elif (num==3) or (num & 3 !=3):
num -=1
else:
num +=1
cnt+=1
return cnt


[Leetcode 421] Maximum XOR of Two Numbers in an Array:在O(n)时间复杂度下求出数组中两数异或结果最大的值

class Solution(object):
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = mask = 0
for x in range(31, -1, -1):
mask += 1 << x
prefixSet = set([n & mask for n in nums])
tmp = ans | 1 << x
for prefix in prefixSet:
if tmp ^ prefix in prefixSet:
ans = tmp
break
return ans


Github答案链接(Python)

Bit Manipulation Solutions
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: