LeetCode(Python3)1.两数之和 2.两数相加

目录

两数之和

两数相加


两数之和

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:

Input:  nums = [2,7,11,15], target = 9
Output:   [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example2: 

Input:  nums = [3,2,4], target = 6
Output:   [1,2]

Example3:

Input:  nums = [3,3], target = 6
Output:   [0,1]


Mentality :

  1. 可以用简单的暴力算法来求解,嵌套两个循环,但是BF毕竟不能满足 Beats100%;
  2. 优化方法:我们可以顺序扫描数组,利用哈希表的性质,对每一个元素,如果能在哈希表中找到给定值的另一个数字,我们就将这结果输出,否则输出None.

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:

LeetCode(Python3)1.两数之和 2.两数相加_第1张图片


两数相加

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: 

Input:  l1 = [2,4,3],  l2 = [5,6,4]
Output:   [7,0,8]

Explanation: 342 + 465 = 807

Example2:

Input:  l1 = [9,9,9,9,9,9,9],  l2 = [9,9,9,9]
Output:   [8,9,9,9,0,0,0,1]


Mentality:

将两个链表的每位相加即可,但要注意各种进位问题。

解决方案:可创建一个虚拟头结点指向真正的head

 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:

LeetCode(Python3)1.两数之和 2.两数相加_第2张图片

你可能感兴趣的