LeetCode | 算法:顺序表求和、单链表相加

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
笔记:
Tips: 空间换时间,使用哈希表记录(number,index)以加速查找
Tricks: 一边循环一边建哈希表,进一步降低时间复杂度

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hash_table = {}
        for i,num in enumerate(nums):
            if (target-num) in hash_table:
                return [hash_table[target-num], i]
            hash_table[num] = i

2. Add Two Numbers

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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
笔记:
(1)创建带头结点的单链表,使得后续的处理可以统一起来;
(2)从头到尾循环一遍即可,关键在于进位传递。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        r = l3 = ListNode(0)  # 初始化求和链表的头结点
        
        p = l1                # 初始化工作指针
        q = l2
        
        carry = 0             #记录是否产生进位
        
        while p or q or carry:
            v1 = v2 = 0
            if p:
                v1 = p.val
                p = p.next
            if q:
                v2 = q.val
                q = q.next
            v3 = (v1 + v2 + carry) % 10
            carry = (v1 + v2 + carry) // 10

            r.next = ListNode(v3)
            r = r.next
            
        return l3.next
 
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容