就业形势太可怕了,行业不断缩招,各大算法岗被各种大神截获,作为一个菜鸟,实在是瑟瑟发抖。身边一大波计算机大神也选择读研,等到毕业找工作就该跪了。从现在起开始坚持刷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