python刚入门,想提高一下,所以来刷刷,但毕竟菜,如有说错,还望指正。
第一题:
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 sameelement twice.
给定一个整数数组,返回两个数字的索引,使它们加起来等于一个特定的目标。
您可以假设每个输入只有一个解决方案,并且不能两次使用相同的元素。
eg:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解决:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) <= 1:
return False
buff_dict = {} #创建一个空字典
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i #将目标的其中的一个数以“键”存入,索引以“值”存入。
第二题:
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.
给定两个非空链表,表示两个非负整数。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将这两个数字相加并以链表的形式返回。
您可以假设这两个数字不包含任何前导零,除了数字0本身。
eg:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
solve:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0#进位符
root = n = ListNode(0)#创建一个链表和一个指向链表开头的指针(可能存疑)
while l1 or l2 or carry:
v1 = v2 = 0#链表中的数
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)#v1+v2+carry/10,carry是商,val是余数
n.next = ListNode(val)
n = n.next
return root.next#遍历链表输出