Q1 Two Sum
Grade:easy
class Solution:
def twoSum(self,nums,target):
d = {}
n = len(nums)
for x in range(n):
if target - nums[x] in d:
return d[target-nums[x]],x
else:
d[nums[x]] = x
思路:相比之下,用数组查找速度会慢很多,这里转换成了字典,同时,需要避免出现 target-nums[x]=num[x]
运行结果展示:
官方题解参考:
方法:哈希表
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
Grade:easy
class Solution:
def isPalindrome(self, x: int) -> bool:
y=str(x)
a=[]
b=[]
for i in range(len(y)-1):
a.insert(i,y[i])
for j in range(len(y)-1):
b.insert(j,y[len(y)-1-j])
if a==b:
return True
else:
return False
思路:用了最粗暴的方法,将设置新的字符串,将原字符串对调导入,对比两个字符串是否相同
运行结果展示:
代码优化:还是用str
class Solution:
def isPalindrome(self, x: int) -> bool:
y = str(x)
return x >= 0 and y == y[::-1]
Grade:normal
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
cnt = 0
result = 0
h1 = l1
h2 = l2
signal = 0
while True:
v = h1.val + h2.val + signal
if v >= 10:
h1.val = v - 10
signal = 1
else:
h1.val = v
signal = 0
if (h1.next is None) or (h2.next is None):
break
else:
h1 = h1.next
h2 = h2.next
if h2.next is not None:
h1.next = h2.next
while (signal == 1) and (h1.next is not None):
h1 = h1.next
v = h1.val + signal
if v >= 10:
h1.val, signal = 0, 1
else:
h1.val, signal = v, 0
if signal == 1:
h1.next = ListNode(1)
return l1
思路:
把l2序列的值加到l1里去、而后返回l1。 步骤主要包括两个循环: (1)当当前位置l1和l2序列都有值时,对应数相加赋到l1序列的相应位置。同时对进位问题进行考虑。 (2)若l1或l2序列在当前位置有一个序列没有值时,开启第二个循环:若l2比l1长,把长的部分接到l1后面。进而考虑进位问题对后续序列的影响。
运行结果展示:
方法优化:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# 创建一个结点值为 None 的头结点, dummy 和 p 指向头结点, dummy 用来最后返回, p 用来遍历
dummy = p = ListNode(None)
s = 0 # 初始化进位 s 为 0
while l1 or l2 or s:
# 如果 l1 或 l2 存在, 则取l1的值 + l2的值 + s(s初始为0, 如果下面有进位1, 下次加上)
s += (l1.val if l1 else 0) + (l2.val if l2 else 0)
p.next = ListNode(s % 10) # p.next 指向新链表, 用来创建一个新的链表
p = p.next # p 向后遍历
s //= 10 # 有进位情况则取模, eg. s = 18, 18 // 10 = 1
l1 = l1.next if l1 else None # 如果l1存在, 则向后遍历, 否则为 None
l2 = l2.next if l2 else None # 如果l2存在, 则向后遍历, 否则为 None
return dummy.next # 返回 dummy 的下一个节点, 因为 dummy 指向的是空的头结点, 下一个节点才是新建链表的后序节点
Tips:
考虑两种特殊情况:
1.长度不相等 123 + 45678
2.有进位的情形 11 + 99 = 110