Merge pull request #607 from Eyjan-Huang/master

更新 面试题python相关代码,题号请参考commit message。一次性交了几道题
This commit is contained in:
程序员Carl
2021-08-17 15:08:05 +08:00
committed by GitHub
4 changed files with 41 additions and 55 deletions

View File

@ -110,13 +110,14 @@ Python
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap={}
for ind,num in enumerate(nums):
hashmap[num] = ind
for i,num in enumerate(nums):
j = hashmap.get(target - num)
if j is not None and i!=j:
return [i,j]
records = dict()
# 用枚举更方便,就不需要通过索引再去取当前位置的值
for idx, val in enumerate(nums):
if target - val not in records:
records[val] = idx
else:
return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
```

View File

@ -111,25 +111,29 @@ Python
```python
class Solution:
def isHappy(self, n: int) -> bool:
set_ = set()
while 1:
sum_ = self.getSum(n)
if sum_ == 1:
def calculate_happy(num):
sum_ = 0
# 从个位开始依次取,平方求和
while num:
sum_ += (num % 10) ** 2
num = num // 10
return sum_
# 记录中间结果
record = set()
while True:
n = calculate_happy(n)
if n == 1:
return True
#如果这个sum曾经出现过说明已经陷入了无限循环了立刻return false
if sum_ in set_:
# 如果中间结果重复出现,说明陷入死循环了,该数不是快乐数
if n in record:
return False
else:
set_.add(sum_)
n = sum_
#取数值各个位上的单数之和
def getSum(self, n):
sum_ = 0
while n > 0:
sum_ += (n%10) * (n%10)
n //= 10
return sum_
record.add(n)
```
Go

View File

@ -121,13 +121,7 @@ Python
```python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
result_set = set()
set1 = set(nums1)
for num in nums2:
if num in set1:
result_set.add(num) # set1里出现的nums2元素 存放到结果
return list(result_set)
return list(set(nums1) & set(nums2)) # 两个数组先变成集合,求交集后还原为数组
```

View File

@ -160,34 +160,21 @@ Python
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lengthA,lengthB = 0,0
curA,curB = headA,headB
while(curA!=None): #求链表A的长度
curA = curA.next
lengthA +=1
while(curB!=None): #求链表B的长度
curB = curB.next
lengthB +=1
curA, curB = headA, headB
"""
根据快慢法则,走的快的一定会追上走得慢的。
在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。
if lengthB>lengthA: #让curA为最长链表的头lenA为其长度
lengthA, lengthB = lengthB, lengthA
curA, curB = curB, curA
那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个
位置相遇
"""
cur_a, cur_b = headA, headB # 用两个指针代替a和b
gap = lengthA - lengthB #求长度差
while(gap!=0):
curA = curA.next #让curA和curB在同一起点上
gap -= 1
while(curA!=None):
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
while cur_a != cur_b:
cur_a = cur_a.next if cur_a else headB # 如果a走完了那么就切换到b走
cur_b = cur_b.next if cur_b else headA # 同理b走完了就切换到a
return cur_a
```
Go