11. 盛最多水的容器
題解 |
left_h = 0
right_h = -1
sc = len(height)-1
max_s= 0
while sc != 0:
if height[left_h] > height[right_h]:
area = sc * height[right_h]
right_h -= 1
else:
area = sc * height[left_h]
left_h += 1
sc -= 1
max_s=max(area,max_s)
return max_s
15. 三數之和
題解 |
n = len(nums)
if not nums or n < 3:
return []
nums.sort()
res = []
for i in range(n):
if nums[i] > 0:
return res
if i > 0 and nums[i] == nums[i - 1]:
continue
L = i + 1 # 令左指針 L=i+1L=i+1
R = n - 1 # 令右指針 R=n-1R=n−1
while L < R: # 當 L<R 時,執行循環
if nums[i] + nums[L] + nums[R] == 0: # 判斷左界和右界是否和下一位置重複,去除重複解。並同時將 L,R 移到下一位置,尋找新的解
res.append([nums[i], nums[L], nums[R]])
while L < R and nums[L] == nums[L + 1]:
L = L + 1
while L < R and nums[R] == nums[R - 1]:
R = R - 1
L = L + 1
R = R - 1
elif nums[i] + nums[L] + nums[R] > 0: # 若和大於0,說明nums[R]太大,R左移
R = R - 1
else: #若和小於 0,說明 nums[L]太小,L 右移
L = L + 1
return res
19. 刪除鏈表的倒數第N個節點
題解 |
root = ListNode(-1)
root.next = head
left = right = root
while n:
right = right.next
n -= 1
while right.next:
right = right.next
left = left.next
left.next = left.next.next
return root.next
20. 有效的括號
題解 |
dic = {'{': '}', '[': ']', '(': ')', '?': '?'}
stack = ['?']
for c in s:
if c in dic: stack.append(c)
elif dic[stack.pop()] != c: return False
return len(stack) == 1
21. 合併兩個有序鏈表
題解 |
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2