目录
两数之和
Question:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example1:
Example2:
Example3:
Mentality :
Code:
from typing import List
nums = [3, 3]
target = 6
def twoSum(nums: List[int], target: int) -> List[int]:
result = {}
for index, num in enumerate(nums):
another = target - num
if another in result:
return [result[another], index]
result[num] = index
return None
print(twoSum(nums, target))
Result:
两数相加
Question:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example1:
Example2:
Mentality:
Code:
# 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:
l3 = ListNode(-1)
head = l3
step = 0
while l1 or l2 or step:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
result = x + y +step
result, step = result % 10, result // 10
head.next = ListNode(result)
head = head.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return l3.next
Result: