day1
Two Sum: https://leetcode.com/problems/two-sum/description/
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].
翻译:给定一个整数数组,返回两个加起来是某特定值的数的索引,假设每次输入只有一个解,并且不能用同一个元素两次。(新手翻译,我到底在说什么)
代码:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j] == target:
return [i,j]
day2
Rotate String: https://leetcode.com/problems/rotate-string/description/
We are given two strings, A
and B
.
A shift on A
consists of taking string A
and moving the leftmost character to the rightmost position. For example, if A = 'abcde'
, then it will be 'bcdea'
after one shift on A
. Return True
if and only if A
can become B
after some number of shifts on A
.
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
Note:
A
andB
will have length at most100
.
翻译:给定两个字符串A和B,将字符串A的字符依次从最头移到最尾,若A终能和B相等则返回True,否则返回False。
代码:
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if A == B:
return True
for i in range(len(A)):
if A[i:]+A[:i]==B:
return True
return False
day3
Reverse Integer: https://leetcode.com/problems/reverse-integer/description/
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
翻译:给定一个整数,将其数字反转。当数字溢出时,返回0。
代码:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
y = -int(str(-x)[::-1])
else:
y = int(str(x)[::-1])
if y < -2147483648 or y > 2147483648:
return 0
return y
day4(没错我又开始了)
invert binary tree
直接暴力贴代码了,尽管最近在学java但还是用我喜欢的python来解
class Solution:
def invertTree(self, root):
if(root == None):
return
righttree = root.right
root.right = self.invertTree(root.left)
root.left = self.invertTree(righttree)
return root
day5
delete node in a linked list
思路是把后一节点的值赋给现有节点,然后删掉后一节点,相当于删除了当前节点
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
day6
two city scheduling
先将差值排序,然后把前半段给A,后半段给B
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
costs.sort(key = lambda x: (x[0]-x[1]))
return sum(x[0] for x in costs[:len(costs)//2]) + sum(x[1] for x in costs[len(costs)//2:])
day7
reverse string
这解法真的不是在逗我。。
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
day8
Random Pick with Weight
今天的题连题目都看不懂,就离谱,写个//todo在这先
day9
queue reconstruction by height
沉迷学习不可自拔。。思路是先把人按身高降序,人数升序排列,然后创建一个holder,遍历人,用人数数值当index插入,不懂的话可以自己用测试用例变换一下
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people = sorted(people, key = lambda x: (-x[0],x[1]))
res = []
for s in people:
res.insert(s[1], s)
return res
day10
coin change 2
动态规划,结合测试用例画个表出来比较容易理解
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [1] + [0] * amount
for c in coins:
for i in range(c, amount + 1):
dp[i] += dp[i - c]
return dp[amount]
day11
power of two
位运算n&(n-1)用来判断是不是2的次方,对于我这种新手记住就好了,先别研究为什么
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
return n & (n-1) == 0
day12
is subsequence
运用迭代器和生成器,还用了return all返回boolean值,同样是人为什么大佬们能想出这种方法。。
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
b = iter(t)
return all((i in b) for i in s)
day13
search insert position
今天头有点疼,明天再做。。//todo
2020年6月11日,天气晴,我打开电脑,想完成昨天没做的算法题,结果莫名其妙打开了姐妹发来的博肖同人文,然后看了一天。。。时间管理崩盘系列。。。
这个思路没什么好讲的了,先add target,再排序,然后读取序号,即使有重复的数字也会返回第一个找到的
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
nums.append(target)
nums.sort()
return nums.index(target)
day14
sort colors
定义3个指针,一个放头一个放尾,还有一个从头开始移动,移动指针q遇到小数往头扔,遇到大数往尾扔
碎碎念:我本来都要讨厌夏天了,可是吃了荔枝之后,我又和夏天和解了,荔枝也太好吃了叭
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
p , q = 0 , 0
k = len(nums) - 1
while q <= k:
if p < q and nums[q] == 0:
nums[p], nums[q] = nums[q], nums[p]
p += 1
elif nums[q] == 2:
nums[q], nums[k] = nums[k], nums[q]
k -= 1
else:
q += 1
day15
今天的题竟然要开会员才能做,开会员是不可能开会员的,留个b站解题视频吧,真没想到我开始用b站是为了刷题。。
https://www.bilibili.com/video/BV1Fg4y1q7Ru?from=search&seid=4277391195308403012
day16
largest divisible subset
动态规划,先排序,建一个list作为holder,如果新加入的数能被list里最大的数整除,那说明它也能被最大的数以前的数整除
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums = sorted(nums)
dp = [[x] for x in nums]
res = []
for i in range(len(nums)):
for j in range(i):
if nums[i] % nums[j] == 0 and len(dp[j])+1 > len(dp[i]):
dp[i] = dp[j] + nums[i:i+1]
if len(dp[i]) > len(res):
res = dp[i]
return res
day17
search in a binary search tree
利用二分查找树的属性,轻松解答~
p.s.最近每天都在头疼,真是邪了门了。。。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
while root:
if root.val == val:
return root
elif root.val > val:
root = root.left
else:
root = root.right
return None
day18
Validate IP Address
用正则表达式来写,还没写出来,明天再写,啊,头疼。。
import re
class Solution:
def validIPAddress(self, IP: str) -> str:
ipv4 = re.compile(r'^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$')
ipv6 = re.compile('^([0-9|a-f|A-F]{1,4}:){7}[0-9|a-f|A-F]{1,4}')
if re.match(ipv4, IP) and re.match(ipv4, IP)[0] == IP:
return "IPv4"
elif re.match(ipv6, IP) and re.match(ipv6, IP)[0] == IP:
return "IPv6"
else:
return "Neither"
day19
Surrounded Regions
有点围棋的感觉,蛮有意思的,但是我还得再研究一下dfs
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board: return
row = len(board)
col = len(board[0])
def dfs(i, j):
if i < 0 or j < 0 or i >= row or j >= col or board[i][j] != 'O':
return
board[i][j] = '#'
dfs(i - 1, j)
dfs(i + 1, j)
dfs(i, j - 1)
dfs(i, j + 1)
for i in range(row):
dfs(i, 0)
dfs(i, col - 1)
for i in range(col):
dfs(0, i)
dfs(row - 1, i)
for i in range(0, row):
for j in range(0, col):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '#':
board[i][j] = 'O'
day20
h index ii
二分查找,最后一步是用来面向测试用例编程的- -
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
l , r = 0 , n - 1
while l <= r:
mid = (l + r)//2
if citations[mid] == n - mid:
return n - mid
if citations[mid] > n - mid:
r = mid - 1
else:
l = mid + 1
return n - l
day21
longest duplicate substring
今天这个是困难,我是不是能直接放弃了。。
well,我真的做不出来,算了
day22
permutation sequence
class Solution:
def getPermutation(self, n: int, k: int) -> str:
from itertools import permutations
tup = list(permutations(list(range(1,n+1)),n))[k-1]
s = ''
for c in tup:
s += str(c)
return s
day23
dungeon game
地下城游戏,哇哦~又是一道困难,我太难了
放弃。。
day24
single number ii
set里不能有重复,乘3恢复原list的同时里面单独的数也会乘3,减去原list,除以2
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return (3*sum(set(nums))-sum(nums))//2
day25
count complete tree nodes
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root: return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
day26
unique binary search trees
写公众号耽搁了两天,今天补上,动态规划真的好难鸭
class Solution:
def numTrees(self, n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - j - 1]
return dp[-1]
day27
find the duplicate number
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow, fast = nums[0], nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return fast
day28
Sum Root to Leaf Numbers
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def find(root, n):
if root is None:
return 0
cur = n * 10 + root.val
if root.right is None and root.left is None:
return cur
return find(root.right, cur) + find(root.left, cur)
return find(root, 0)
day29
perfect squares
最近没空写鸭先打个//todo吧
day30
Reconstruct Itinerary
day31
unique paths
day32
word search 2
先告一段落等我把欠的题补完先。。