自定义博客皮肤VIP专享

*博客头图:

格式为PNG、JPG,宽度*高度大于1920*100像素,不超过2MB,主视觉建议放在右侧,请参照线上博客头图

请上传大于1920*100像素的图片!

博客底图:

图片格式为PNG、JPG,不超过1MB,可上下左右平铺至整个背景

栏目图:

图片格式为PNG、JPG,图片宽度*高度为300*38像素,不超过0.5MB

主标题颜色:

RGB颜色,例如:#AFAFAF

Hover:

RGB颜色,例如:#AFAFAF

副标题颜色:

RGB颜色,例如:#AFAFAF

自定义博客皮肤

-+
  • 博客(36)
  • 收藏
  • 关注

原创 Leetcode 520. Detect Capital (python+cpp)

题目解法:只需要注意一下python里面is_upper的用法即可。C++里面直接进行比较就好python版本class Solution: def detectCapitalUse(self, word: str) -> bool: capital_pos = [] for i,c in enumerate(word): if c.isupper(): capital_pos.append(i)

2020-09-30 09:55:55 172

原创 Leetcode 140. Word Break II (python+cpp)

Leetcode 140. Word Break II题目解法1:动态规划+暴力递归解法2:recursion+memorization总结题目解法1:动态规划+暴力递归首先用word break I的方法来判断是否能够拆分能拆分之后,暴力recursion解出所有答案class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: def check(s):

2020-09-30 09:46:13 562

原创 计算IOU of two rectangles

题目给两个rectangle,boxA:[x1,y1,x2,y2], boxB:[x3,y3,x4,y4]。前两个坐标代表upper left point,后两个座标代表bottom right point,并且假设x向右为正方向,y向下为正方向。主要思想是,相交的区域的upper left point是A和B upper left point中的一个,相交的区域的的bottom right point是A和B的bottom point中的一个。代码如下:def cal_iou(boxA,boxB):

2020-09-28 14:33:04 167

原创 求vector shift次数

题目给定两个vector,比如A = [9,8,7,6,5,4,3,2,1],B = [7,6,5,4,3,2,1,9,8]。求A经过多少次shift到B。要求复杂度小于O(n),n为vector长度思路如果能够得到任意一对相同元素在vector A,B中的位置,那么shift次数就是两个位置相减。假设看A中的前m个元素,如果在B中从0开始,以m为间隔取元素,那么必定有一次或者多次这个B中的元素会是A中的前m个元素。这样子的复杂度是O(m)*O(n/m). 所以当m为sqrt(n)时复杂度最小。具体

2020-09-28 14:07:31 269

原创 Leetcode 36. Valid Sudoku (python)

Leetcode 36. Valid Sudoku题目解法:题目解法:这道题不难,关键在于找到(i,j)位置的元素怎样同时判断row,col和box的情况。对于row,col和box,分别对应9行,9列和9个box。用三个长度为9元素为字典的list来对应class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: row_dic = [collections.defaultdict

2020-09-28 11:57:41 366

原创 Leetcode 311. Sparse Matrix Multiplication (python)

Leetcode 311. Sparse Matrix Multiplication题目解法:暴力解法2:题目解法:暴力这边主要讲一下怎么做矩阵乘法。假设我们有矩阵A,B,结果是C,那么C[i][k] += A[i][j]*B[j][k]从矩阵乘法的维度变化来考虑就可以理解了。遍历的顺序不重要,下面几种都是ok的class Solution: def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[

2020-09-27 09:30:50 1167

原创 Leetcode 269. Alien Dictionary(python)

Leetcode 269. Alien Dictionary题目解法:拓扑排序题目解法:拓扑排序这道题的解法leetcode官方写的非常好,也非常有助于理解拓扑排序,建议仔仔细细地看他的官方解析class Solution: def alienOrder(self, words: List[str]) -> str: # create adject matrx of the graph adj_list = collections.defaultdic

2020-09-26 07:25:47 2424

原创 Leetcode 43. Multiply Strings (python+cpp)

Leetcode 43. Multiply Strings题目解法:题目解法:class Solution: def multiply(self, num1: str, num2: str) -> str: if num1=='0' or num2=='0': return '0' product = [0]*(len(num1)+len(num2)) pos = len(product)-1

2020-09-26 06:12:01 223

原创 string的加/减/乘 (python)

题目描述以string表示的两个数字,求他们的加/减/乘,最后结果以string返回加法:def add_string(num1, num2): ans = '' carry = 0 p1 = len(num1) - 1 p2 = len(num2) - 1 while p1>=0 or p2>=0: v1 = ord(num1[p1]) - ord('0') if p1 >= 0 else 0 v2 = or

2020-09-26 06:07:29 1720

原创 Leetcode 773. Sliding Puzzle (python+cpp)

题目解法:BFS把board的状态看成是图的节点,相互之间的转换看成是边,那么其实这个就是找节点之间最短距离的问题,套BFS的模板就可以。需要注意的几个点:因为list是unhashable的,所以不能加到visited的set中,所以这边牵涉到list跟字符串之间的一些转换list中某个元素在摊平了之后的string中的位置对应关系。假设list中的位置是[x,y],对应string中的位置是x*num_col+y.反过来如果在string中的位置是k,那么在list中对应位置是[k//nu

2020-09-25 14:49:14 533

原创 Leetcode 867. Transpose Matrix (python+cpp)

Leetcode 867. Transpose Matrix题目解法:题目解法:构建一个空矩阵,行数是原来矩阵的列数,列数是原来矩阵的行数。然后遍历原矩阵,假设元素在原矩阵的[i,j],将空矩阵的[j,i]位置放上当前元素class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: r,c = len(A),len(A[0]) ans = [[N

2020-09-25 14:26:24 123 1

原创 Leetcode 1057. Campus Bikes (python)

Leetcode 1057. Campus Bikes题目解法1:暴力排序解法2:heap代替暴力排序题目解法1:暴力排序首先理解这道题目一定要到位。不是说从bike去找worker,也不是从worker去找bike。如果一开始陷入了这种错误思路,就会想到BFS,把题目搞得很复杂。正确的理解是这样的,找到距离最近的pair,如果距离最近的pair有多个,那么先要选小的worker_id,比如worker1和worker2和bike1距离一样,那么要选worker1.然后如果worker1和bike

2020-09-25 14:20:34 416

原创 Leetcode 1235. Maximum Profit in Job Scheduling (python)

Leetcode 1235. Maximum Profit in Job Scheduling题目解法1:dp解法2:dp+binary search题目解法1:dp这倒题目用dp来做是挺明显的,但是dp的元素代表什么很关键。如果dp元素代表时间的话,那这个题目就很难做了。正确的做法应该是用区间来代表dp的元素,这样就变成了对于每个元素取或者不取两种情况了。具体的解法如下:将各个区间按照结尾进行排序dp[i]代表从前i个区间中选择,最多可以获取多大的利润对于第i个区间,分取和不取两种情况如

2020-09-25 08:06:05 1545

原创 二分搜索总结

对于二分搜索,一共有四种常见的写法,左开右闭,左闭右开,左开右开,左闭右闭。实际上只要透彻的理解一种其他的就应该也能够明白。首先来讲什么是闭和开。对于二分搜索,general的来说我们会有一个check函数,这个check函数决定了下一步的搜索往哪里走,而且一定是能确定往哪一边走才是严格意义上的二分。这边的闭对应的是check函数的结果为True,而开相反的对应的就是False。那么对于左闭右开,意味着对left指针所指的元素所对应的check结果始终会是True,相反的right指针对应的始终是Fals

2020-09-24 14:40:41 298

原创 Leetcode 576. Out of Boundary Paths (python+cpp)

Leetcode 576. Out of Boundary Paths题目解法:暴力dfs(TLE)解法2:dfs+memorization题目解法:暴力dfs(TLE)这边要注意的是,不需要判断当前位置是否被访问过。因为问的是多少条不同的路径,只要开始位置不同,那么路径就不同dfs写法1:这种写法完全可以,但是如果想要加memorization就不方便了,所以写法2更好class Solution: def findPaths(self, m: int, n: int, N: int,

2020-09-23 08:00:02 209

原创 Leetcode 415. Add Strings (python+cpp)

Leetcode 415. Add Strings题目解法:follow up 1:两个string相减follow up2:两个string相加,但是有可能有负号题目解法:这边默认肯定是不能用强制类型转换的python:class Solution: def addStrings(self, num1: str, num2: str) -> str: ans = '' pt1 = len(num1)-1 pt2 = len(num2

2020-09-23 07:53:04 337

原创 根据距离求cluster

题目:解法:解法与上面说的思路一样import mathimport collectionsdef cal_dis(x1,y1,x2,y2): return math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))k = 7points = [(0,1),(0,2),(0,3),(0,4),(0,10),(0,11),(0,100),(0,101)]graph = collections.defaultdict(set)for i in rang

2020-09-20 09:30:10 424

原创 Leetcode 239. Sliding Window Maximum (python&c++)

Leetcode 239. Sliding Window Maximum题目:解法:deque实现的单调队列题目:解法:deque实现的单调队列关于单调队列的解释:https://medium.com/algorithms-and-leetcode/monotonic-queue-explained-with-leetcode-problems-7db7c530c1d6举个例子来说明单调队列,现在有个递减的单调队列[6,4,3]:新元素为2,队列变为[6,4,3,2]新元素为5,队列变为[6

2020-09-20 08:59:22 333

原创 Leetcode 432. All O`one Data Structure (python)

Leetcode 432. All O`one Data Structure题目解法1:暴力O(N)follow up:O(1)解法题目解法1:暴力O(N)class AllOne: def __init__(self): """ Initialize your data structure here. """ self.data = {} def inc(self, key: str) ->

2020-09-20 06:59:00 352

原创 Leetcode 273. Integer to English Words (python)

Leetcode 273. Integer to English Words题目解法:题目解法:建议直接看lc官网:https://leetcode.com/problems/integer-to-english-words/class Solution: def numberToWords(self, num: int) -> str: # 2^31 = 2 147 483 648 def one(num): switcher

2020-09-20 06:42:33 239

原创 Leetcode 1400. Construct K Palindrome Strings (python)

Leetcode 1400. Construct K Palindrome Strings题目解法:题目解法:其实题目很简单,只需要数出有多少个字符是出现了奇数词的,因为在一个回文字符串中,至多只能出现一种个数为奇数的字符,所以这个数必须要小于我们总共形成的回文字符串个数。而且一旦这个条件满足,剩下的都是出现偶数次数的字符,一定能构造出符合题意的k个回文字符串class Solution: def canConstruct(self, s: str, k: int) -> bool:

2020-09-17 04:38:03 210

原创 Leetcode 132. Palindrome Partitioning II (python+cpp)

Leetcode 132. Palindrome Partitioning II题目解法1:backtracking暴力解法(TLE)解法2:O(N^3)动态规划解法3:O(N^2)动态规划题目解法1:backtracking暴力解法(TLE)class Solution: def minCut(self, s: str) -> int: def helper(i,count): nonlocal ans if i==le

2020-09-16 13:30:37 324

原创 Leetcode stock买卖问题集合

Leetcode stock买卖问题集合题目1:解法:题目2:解法:动态规划题目1:解法:因为卖必须发生在买之后,所以用一个变量来储存当前位置之前的数字中的最小值,而另一个变量储存当前卖掉可以获得的最大值class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) min_buy = float('inf') max_profit = 0

2020-09-16 13:30:15 336 1

原创 Leetcode 290. Word Pattern & 291. Word Pattern II (python)

Leetcode 290. Word Pattern & 291. Word Pattern IIword pattern题目解法:双hashmapword pattern II题目:解法:双hashmap+backtrackingword pattern题目解法:双hashmap判断他们是否matching的关键在于,pattern中的某个字母和s中的单词是不是双向1-1对应的。要表达这种双向1-1对应的关系可以用两个字典,每个字典表示一种映射方向class Solution:

2020-09-14 08:26:52 681

原创 Leetcode 792. Number of Matching Subsequences (python)

Leetcode 792. Number of Matching Subsequences题目解法1:brutal force (TLE)解法2:题目解法1:brutal force (TLE)用双指针法判断某个word是不是S的subsequence。class Solution: def numMatchingSubseq(self, S: str, words: List[str]) -> int: def isSubsequence(word):

2020-09-11 13:16:57 330

原创 Leetcode 465. Optimal Account Balancing (python+cpp)

Leetcode 465. Optimal Account Balancing题目解析:题目解析:这个题目手下需要进行一些预处理,这一系列的转账可以被全部简化成每个账户进行这些转账之后最后需要支出或者收入多少钱。这个问题有许多的解法,但是我个人认为比较make sense的一种就是利用backtracking枚举所有可能的方式。具体如下:从第一个账户开始,我们现在的目标是,清空第一个账户,那么就意味着可以将第一个账户的余额加到后面任意一个非0切正负与第一个账户余额相反的账户上然后进行下一层d

2020-09-09 13:12:16 967

原创 完全背包和0,1背包的差别

完全背包与0,1背包的差别完全背包与0,1背包的唯一差别在于物品是否能被复用。两种题目实现的差别也非常非常小。举例说明:nums=[1,2,3,4,5],target=11,求用nums中任意个数字是否能组成target。0,1背包情况:每个数字只能被用一次状态转移方程:dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i]]dp[i][j]代表只用前i个数字的情况下是否能组成j完全背包情况:每个数字可以被用无限次状态转移方程:dp[i][j] = dp[i-1]

2020-09-08 13:20:39 2736 2

原创 Leetcode 1522. Diameter of N-Ary Tree (python+cpp)

Leetcode 1522. Diameter of N-Ary Tree题目:解法:题目:解法:这是543的follow up,解法几乎是一样的,只不过左子树和右子树的深度替换成所有子树里面深度最大的两个class Solution: def diameter(self, root: 'Node') -> int: """ :type root: 'Node' :rtype: int """ def g

2020-09-07 06:41:54 407

原创 Leetcode 23. Merge k Sorted Lists (python+cpp)

Leetcode 23. Merge k Sorted Lists题目:解法1:heap解法2:divide and conquer题目:解法1:heap利用heap,保持heap size在k,这边在python里可以用priorityqueue也可以直接用heap。用priorityqueue的话python3不行,因为python3里面定义不太一样:python3 use from queue import PriorityQueue, instead of from Queue. (the

2020-09-07 05:49:10 706

原创 Leetcode 684. Redundant Connection (python)

Leetcode 684. Redundant Connection题目解法1:dfs解法2:unionfind题目解法1:dfs一次构建图,返回第一组成环的边。class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: def dfs(source,target): if source in seen:

2020-09-06 11:41:25 440

原创 Leetcode 305. Number of Islands II (python)

Leetcode 305. Number of Islands II题目:解法:hashmap题目:解法:hashmap这道题是number of islands的follow up,关于number of islands见另外一篇博客。这道题目的难点在于,

2020-09-06 10:14:22 1013

原创 Leetcode 200. Number of Islands (python+cpp)

Leetcode 200. Number of Islands题目解法1:DFS解法2:union find题目解法1:DFS每次遇到1时进行dfs,并将访问到连在一起的1都进行mark。总共进行DFS的次数就是island的个数python代码:class Solution: def numIslands(self, grid: List[List[str]]) -> int: def helper(i,j): if i<0 or i

2020-09-05 04:53:25 662

原创 Leetcode 977. Squares of a Sorted Array (python+cpp)

Leetcode 977. Squares of a Sorted Array题目解法1:two pass with two pointer解法2:improved two pass with two pointers解法3:one pass with two pointers题目解法1:two pass with two pointerclass Solution: def sortedSquares(self, A: List[int]) -> List[int]:

2020-09-03 13:07:56 332

原创 Leetcode 124. Binary Tree Maximum Path Sum (python+cpp)

Leetcode 124. Binary Tree Maximum Path Sum题目解法:recursion题目解法:recursion参考leetcode官方解法:https://leetcode.com/problems/binary-tree-maximum-path-sum/solution/关键点在于两个,一个是用全局的变量来保存最大值,另一个点在于如何计算以某个节点为根节点所能得到的路径最大值。left_gain和right_gain得到的方式也很需要思考python代码:c

2020-09-03 12:16:11 279

原创 Leetcode 113. Path Sum II (python+cpp)

Leetcode 113. Path Sum II题目:解法:类似backtracking题目:解法:类似backtracking在path sum I的基础上稍作改动即可class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: def helper(node,curr_sum,curr_path): if not node:

2020-09-03 08:51:42 169

原创 Leetcode 112. Path Sum (python+cpp)

Leetcode 112. Path Sum题目:解法:简单递归题目:解法:简单递归class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: def helper(node,curr_sum): if not node.left and not node.right: return curr_sum+node.val == sum

2020-09-03 08:46:49 173

空空如也

空空如也

TA创建的收藏夹 TA关注的收藏夹

TA关注的人

提示
确定要删除当前文章?
取消 删除