领扣-哈希表练习
136.只出现一次的数字
# -*- coding: utf-8 -*-
import collections
def singleNumber(nums):
"""
:type nums: List[int]
:rtype: int
"""
s = []
for i in nums:
if i not in s:
s.append(i)
elif i in s:
s.remove(i)
return s[0]
def singleNumber2(nums):
s = {}
for i in nums:#i是列表中的每个元素
if i in s.keys(): #在s的键中
s.pop(i) #根据键删除值
else:
s[i] = 1 #{1:1,2:1,4:1}
print(s.keys())
return list(s.keys())[0] #无[0]的话为列表
#思路是运用按位异或运算符,当两对应的二进位相异结果为1
def singleNumber3(nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in nums:
res^=i
return res
#4:100^000=100(4)
#1: 100^001=101(5)
#2: 101^010=111(7)
#1: 111^001=110(6)
#2: 110^010=100(4)
def singleNumber4(nums):
"""
:type nums: List[int]
:rtype: int
"""
x= [i for i in nums if nums.count(i) == 1]
return x[0]
def singleNumber5(nums):
"""
:type nums: List[int]
:rtype: int
"""
x = collections.Counter(nums)
#for key,value in x.items():
for key, value in x.items():
if value < 2:
return key
def singleNumber6( nums):
"""
:type nums: List[int]
:rtype: int
"""
while len(nums) != 1:
lastCha = nums.pop() #2、弹出最后一个元素
if lastCha in nums:
nums.remove(lastCha)
else:
return lastCha
return nums[0]
def singleNumber7(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()#从小到大排序
for i in range(0, len(nums) - 1, 2):
if nums[i] != nums[i + 1]:
return nums[i]
return nums[-1]
if __name__ == '__main__':
print(singleNumber([4,1,2,1,2]))
print(singleNumber2([4, 1, 2, 1, 2]))
print(singleNumber3([4, 1, 2, 1, 2]))
print(singleNumber7([4, 1, 2, 1, 2]))
202快乐数
# -*- coding: utf-8 -*-
class Solution:
def isHappy1(self, n):#方法一:一直调用isHappy函数,try...except Exception as e,超出时间限制
try:
if n == 1:
return True
else:
new = str(n)
sum = 0
for c in new:
sum += int(c) ** 2
return self.isHappy1(sum)
except Exception as e:
return False
#思路
class Solution2:
def isHappy(self, n):
temp = []
while True:
n = self.get_add(n)
if n == 1:
return True
elif n in temp:
return False
else:
temp.append(n)
def get_add(self, n):
ret = 0
while n != 0:
g = n % 10
ret += g ** 2
n = int(n / 10)
return ret
class Solution3(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
d = []
while True:
l1=list(str(n))
l2=list(l1)
l3=map(int,l1)
l = list(map(int,list(str(n))))
m = 0
for i in l:
m += i**2
if m in d:
print(d)
return False
if m == 1:
print(d)
return True
#d[m] = m
d.append(m)
n = m
#print(happy(36))
u=Solution3()
print(u.isHappy(19))