LeetCode学习笔记-Day1

来源:互联网 发布:手机切图软件 编辑:程序博客网 时间:2024/06/05 07:07

Problem 1

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Answer

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

遍历nums列表,将差值作为key,其索引为value储存到字典中,在后面的循环中,如果列表中有这个差值,则返回其索引和对应的字典的值。

Problem 2

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Answer

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        temp = 0        root = l3 = ListNode(0)        while l1 or l2 or temp:            a = b = 0            if l1:                a = l1.val                l1 = l1.next            if l2:                b = l2.val                l2 = l2.next            c = a + b + temp            if c>= 10:                 l3.next = ListNode(c % 10); temp = 1            else:                 l3.next = ListNode(c); temp = 0             l3 = l3.next        return root.next

python中列表、字典、包括这里的类,变量赋值时属于浅拷贝,类似于c++中的引用,因此root所对应的地址不会发生改变。例如:

>>> root = l3 = ListNode(0)>>> id(root)49442152L>>> id(l3)49442152L>>> l3.next = ListNode(1)>>> l3 = l3.next>>> id(l3)49039680L>>> id(root.next)49039680L
原创粉丝点击