LeetCode 笔记一 两数和找索引以及链表求和

LeetCode 笔记一 2019/09/23

就业形势太可怕了,行业不断缩招,各大算法岗被各种大神截获,作为一个菜鸟,实在是瑟瑟发抖。身边一大波计算机大神也选择读研,等到毕业找工作就该跪了。从现在起开始坚持刷LeetCode,希望一年半后能发挥一点作用吧!
先用Python3进行编程吧…

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,
return [0, 1]

Code

一开始仅从题目出发,很自然的写成

class Solution:
	def twoSum(self, nums: List[int], target:int) -> List[int]:
		for i in nums:
			if (target - i) in nums:
				return [nums.index(i), nums.index(target - i)]

看起来好容易啊!按Run Code也没有问题,完美~
结果提交,妥妥的报错。

Input: 		[3,2,4], 6
Output: 	[0, 0]
Expected:   [1, 2]

还是太天真了…于是重新写一个。先从循环的角度入手,就是贼简单那种两层循环。

class Solution:
	def twoSum(self, nums: List[int], target: int) -> List[int]:
		for i in range(len(nums)):
			for j in range(i+1, len(nums)):
				if target - nums[i] == nums[j]:
					return [i, j]

果然,两层循环妥妥的成功了,然而运行时间跟内存gg了

29/29 test cases passed
Runtime: 5356 ,s
Memory Usage: 14.9 MB

运行时间成功打败了14.75%,占用内存成功打败11.62%!恭喜恭喜…
继续编吧…然后看到有人说可以写字典,就试了一下。

class Solution:
	def twoSum(self, nums: List[int], target: int) -> List[int]:
		num_dict = {}
		for i, num in enumerate(nums):
			temp = target - num
			if n in num_dict :
				return [num_dict [n], i]
			else:
				num_dict [num] = i       

发现运行时间还可以,但内存还是有点大。运行时间超过87.75%, 内存超过9.53%…还是并没有很好。

29 / 29 test cases passed.
Runtime: 56 ms
Memory Usage: 15 MB

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.

Code

这个题涉及到链表,用的单向链表,要注意链表的指向,可以构建一个临时的链表传递指针。

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

class Solution:
	def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNoode:
	carry = 0
	r = temp = ListNode(0)
	while (l1 != None) or (l2 != None) or carry:
		if l1 != None:
			carry += l1.val
			l1 = l1.next
		if l2 != None:
			carry += l2.val
			l2 = l2.next
			
		temp.next = ListNode(carry % 10)
		temp = temp.next
		carry //= 10
	return r.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值