只出现一次的数字
class Solution:
#使用字典的方法
def singleNumber(self, nums: List[int]) -> int:
map_=dict() #统计数组中元素出现的频率
for i in nums:
map_[i]=map_.get(i,0)+1
for key,freq in map_.items():
if freq==1:
return key
#第二种方法:做异或运算
#任何数与0异或,还是自身;任何数与自身异或,结果为0;异或运算满足结合律
def singleNumber2(self, nums: List[int]) -> int:
result=0
for i in range(len(nums)):
result=result^nums[i]
return result
a=Solution()
nums_str=input()
nums=[int(n) for n in nums_str.split()]
print(a.singleNumber(nums))
环形链表(判断链表中是否有环)
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
#快慢指针
if not head or not head.next:
return False
slow=head
fast=head.next
while slow!=fast:
if not fast or not fast.next:
return False
slow=slow.next
fast=fast.next.next #比慢指多走一步
return True