自定义博客皮肤VIP专享

*博客头图:

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

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

博客底图:

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

栏目图:

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

主标题颜色:

RGB颜色,例如:#AFAFAF

Hover:

RGB颜色,例如:#AFAFAF

副标题颜色:

RGB颜色,例如:#AFAFAF

自定义博客皮肤

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

原创 1419. Minimum Number of Frogs Croaking (python)

题目解法:这个题目有点意思的,比较巧妙。我们需要找的是,这五个字母在某个时间出现的最大次数。限制条件是,每当遇到一个k的时候,放掉一只青蛙。同时需要检查给的字符串是不是无效,依照两个规则判断:如果出现了一个字符,但是应该出现在他之前的字符没有出现,比如直接来个r,那就无效当所有过程结束,所有的字符应该要刚好形成完整的若干个croak接下来的就是实现问题了class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -&

2020-11-27 12:27:52 20

原创 Leetcode 1424. Diagonal Traverse II (python)

题目解法1:排序这道题关键在于在同一条对角线上的元素行数和列数的和是相同的。所以将每个元素按照(r+c,r,val)储存,然后先按照第一个元素升序排序,其次按照第二个元素降序排序即可这边有个要注意的点是这两个排序是一个升序一个排序,而且要在第一个排序的基础上进行排序,在python里面需要用sorted函数,并且secondary element,再排primary element,详细参见:https://docs.python.org/3/howto/sorting.htmlclass So

2020-11-26 05:50:10 52

原创 Leetcode 1423. Maximum Points You Can Obtain from Cards (python)

题目解法1:O(n)利用prefix sum,遍历k种不同组合class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: prefix_sum = [0] tmp = 0 for card in cardPoints: tmp += card prefix_sum.append(tmp)

2020-11-26 05:38:52 61

原创 Leetcode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (python)

题目解法1:二分判定+sliding window由于所求的这个最大长度一定唯一而且会在连续的整数中产生,所以可以用二分判定选取一个特定长度,判断是否存在特定长度的subarray符合条件对于每次判定,使用sliding window的方法,所以每次判定复杂度O(n)总的复杂度O(nlogn)class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: n = le

2020-11-23 08:56:28 18

原创 Leetcode 1442. Count Triplets That Can Form Two Arrays of Equal XOR (python)

题目解法:prefix XOR这道题目解法基于几个结论:We are searching for sub-array of length ≥ 2 and we need to split it to 2 non-empty arrays so that the xor of the first array is equal to the xor of the second array. This is equivalent to searching for sub-array with xor =

2020-11-22 11:16:22 10

原创 Leetcode 1443. Minimum Time to Collect All Apples in a Tree (python)

题目解法1:利用dfs,找出所有的在摘苹果的过程中会被访问的边。这些被访问的边数*2就是答案这种做法需要保存当前路径,当发现当前路径包含苹果时,将这些边加入访问列表。这样做的坏处在于,每条边可能被加入多次,意味着时间复杂度的增加,事实证明这种做法确实不都快,刚刚过TLE的线。但利用字典或者set,还是可以不重复的记录摘苹果时需要被访问的边class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: L

2020-11-22 10:51:11 8

原创 Leetcode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List (python)

题目解法1:set这种解法比较巧妙的运用了set和&操作,但速度挺慢class Solution: def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]: A = favoriteCompanies dic = {tuple(x):ind for ind,x in enumerate(A)} A.sort

2020-11-20 11:37:52 6

原创 Leetcode 1451. Rearrange Words in a Sentence (python)

题目解法1:同时sort单词长度和indexclass Solution: def arrangeWords(self, text: str) -> str: text = text.split() len_ind_list = [] for i, word in enumerate(text): len_ind_list.append((len(word),i,word)) le

2020-11-20 11:33:46 8

原创 Leetcode 1457. Pseudo-Palindromic Paths in a Binary Tree (python)

题目解法1:利用backtracking生成每条根节点到叶结点的路径,在利用字典注意判断。一条路径的permutaion要可以回文的条件是奇数个的数字个数只能是0或1class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: def dfs(node,path): if not node: return

2020-11-19 11:01:59 8

原创 Leetcode 1456. Maximum Number of Vowels in a Substring of Given Length (python)

题目解法1:stackclass Solution: def maxVowels(self, s: str, k: int) -> int: if len(s)<k: return 0 candidates = ['a','e','i','o','u'] ans = 0 window = collections.deque() for c in s[:k]:

2020-11-19 10:56:34 12

原创 Leetcode 74. Search a 2D Matrix (python+cpp)

题目解法:二分搜索可以根据大小关系直接降成一维,然后二分搜索class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or not matrix[0]: return False arr = [] for row in matrix: arr += ro

2020-11-18 14:30:06 3

原创 Leetcode 1466. Reorder Routes to Make All Paths Lead to the City Zero (python)

题目解法:这道题目有个关键是,图里面n个节点,有n-1条边,而且题目也提示了可以看作是一棵树。关键在于理解每个节点都指向0代表什么:代表的是每个以0作为根节点,每个叶节点到根节点的路径都是子节点指向父节点的。比如第一个例子,只需要保证2到0和5到0这两条路径都是子节点指向父节点的。而对于connections里面的边,一定是有一个在树里是父节点,另一个是子节点,我们只需要保证这两个节点的相对顺序即可,那么解法就很清晰了:从0节点出发,利用BFS或者DFS遍历一遍树,并且保存每个节点被访问的相对顺序

2020-11-18 14:09:27 14

原创 Leetcode 149. Max Points on a Line (python)

题目暴力解法:O(n^3)class Solution: def maxPoints(self, points: List[List[int]]) -> int: n = len(points) if n<=1: return n max_count = 0 for i in range(n): x1,y1 = points[i]

2020-11-17 14:31:22 8

原创 Leetcode 1472. Design Browser History (python)

题目解法关键在与读懂题意,题目很简单需要储存之前访问过的history列表,以及当前所在page在history中的位置对于visited,找到当前page,删除当前page之后所有的历史,在当前page后新加visited的page,更新现在page的位置back和forward操作,history不用变,只需要判断前移或者后移会不会超出边界即可class BrowserHistory: def __init__(self, homepage: str): se

2020-11-17 06:49:28 12

原创 1482. Minimum Number of Days to Make m Bouquets (python+cpp)

题目解法:二分判定这道题关键在于想到用二分判定去做。因为假设m天能够成功的话,那么大于m的天数一定也是可以的。反过来说,m天不可以,那么小于m的天数一定都不可以,这样子其实我们只需要去找False和True的分界线即可。关于每次判定,相当于从一个固定的序列判断是否成功,很简单的O(n)就可以做。所以总体复杂度是O(nlogn)python版本class Solution: def minDays(self, bloomDay: List[int], m: int, k: int) -&g

2020-11-16 12:43:31 57

原创 Leetcode 1515. Best Position for a Service Centre (python)

题目解法:gradient descent还是第一次碰到用梯度下降做的题目。这个题目是没有办法找到精确解的,所以就能想到梯度下降了。这边梯度下降还得调一调参数,固定learning rate不太行,需要learning rate decay。也可以加momentum加快速度with lr decayclass Solution: def getMinDistSum(self, positions: List[List[int]]) -> float: n = len(

2020-11-13 10:49:42 15

原创 Leetcode 1488. Avoid Flood in The City(python)

题目解法:贪心总体思想是把0的位置储存下来。每当遇到已经满的湖泊,查看两个问题:1)是否能够干燥他 2)能干燥他的符合条件的最早位置不能干燥有两种情况,一种是现在就没有保存好的0,第二种是,保存好的0出现在这个湖泊之前被下雨满的时间之前。能干燥的情况,我们遵循贪心思想,找到最早的符合条件的干燥日。也就是之前湖泊下满之后出现的第一个0,这边用二分搜索找到这个位置。bisect.bisect_right(array, index)返回array中从左往右第一个比index大的位置class Sol

2020-11-12 09:35:28 46

原创 Leetcode 1487. Making File Names Unique (python)

题目解法1:暴力TLEclass Solution: def getFolderNames(self, names: List[str]) -> List[str]: seen = {} ans = [] for name in names: if name not in seen: ans.append(name) seen[name] = True

2020-11-12 09:29:14 43 2

原创 Leetcode 1498. Number of Subsequences That Satisfy the Given Sum Condition (python)

题目解法:解析见注释class Solution: def numSubseq(self, nums: List[int], target: int) -> int: # main idea: sort the nums first. Then we can search for low bound and upper bound and count. For a fixed lower bound, we find the most right upper bound

2020-11-11 10:24:01 44

原创 Leetcode 1497. Check If Array Pairs Are Divisible by k (python)

题目解法:解析见注释class Solution: def canArrange(self, arr: List[int], k: int) -> bool: # main idea: First, we only need to consider the remain of every numbers. Second, we find the match between remains and see if all teh remains can form a val

2020-11-11 10:22:15 44

原创 Leetcode 1504. Count Submatrices With All Ones (python)

题目解法1:枚举上下边界,将二维问题转化为1维vector的情况来做class Solution: def numSubmat(self, mat: List[List[int]]) -> int: m,n = len(mat),len(mat[0]) partial_sum = [[0]*n for _ in range(m+1)] for i in range(n): tmp = 0

2020-11-11 03:33:29 31

原创 Leetcode 1514. Path with Maximum Probability (python)

题目解法:bellman ford这个题目本质上还是个图中求最短路径的问题参考leetcode Path With Minimum Effort解法class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = collections.defaultdict(li

2020-11-06 10:51:40 54

原创 Leetcode 1519. Number of Nodes in the Sub-Tree With the Same Label (python)

题目解法:这个题目需要好好理解,首先题目没有给根几点,而只是给了根节点的值。同时提供的边是没有方向的,可能是parent指向child,也可以是child指向parent。因为只提供了根节点的值和边,所以我们只能通过BFS来遍历整棵树,通过一个visited数组保证访问方向是从parent到child的。同时关于我们要求的答案,需要maintain一个count数组,因为都是lowercase,所以每行26的长度即可,这样方便后续的更新同时这边利用了树形递归的方法,从child节点到parent

2020-11-05 10:40:14 49

原创 Leetcode 1529. Bulb Switcher IV (python)

题目解法:每次有连续的两个字符不同就需要一次反转class Solution: def minFlips(self, target: str) -> int: if not target: return 0 if target[0] == '0': count = 0 else: count = 1 for i in range(1,len(targe

2020-11-05 07:07:23 18

原创 Leetcode 1530. Number of Good Leaf Nodes Pairs (python)

题目解法:将树转换成图,然后从每个leaf node开始进行BFS。虽然这种解法没有这么快,但是我觉得很标准。所有判断有没有出现过的node都用字典实现O(1)的查找时间复杂度要注意两点:不同的节点值可能会相同(nodeA,nodeB)和(nodeB,nodeA)算一个pair# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None

2020-11-05 06:57:41 70

原创 Leetcode 1535. Find the Winner of an Array Game (python)

题目解法用单个count来记录某个位置能赢的次数即可class Solution: def getWinner(self, arr: List[int], k: int) -> int: n = len(arr) if k>=n-1: return max(arr) if k==1: return max(arr[0],arr[1]) curr_max

2020-11-03 09:00:49 9

原创 Leetcode 1536. Minimum Swaps to Arrange a Binary Grid (python)

题目解法:将2D问题转化为1D,然后贪心的移动class Solution: def minSwaps(self, grid: List[List[int]]) -> int: n = len(grid) # take this as a 1-d problem,count the continues 0 from the end in every row. What we need to do is to put the rows at the cor

2020-11-03 08:57:11 215

原创 Leetcode 529. Minesweeper (python)

题目Let’s play the minesweeper game (Wikipedia, online game)!You are given a 2D char matrix representing the game board. ‘M’ represents an unrevealed mine, ‘E’ represents an unrevealed empty square, ‘B’ represents a revealed blank square that has no adjace

2020-11-02 15:34:04 44

原创 Leetcode 1545. Find Kth Bit in Nth Binary String (python)

题目解法:递归class Solution: def findKthBit(self, n: int, k: int) -> str: # if n=1, meaning s='0' if n==1: return '0' # compute length of current string lenth = 2**n - 1 # if k at the middle

2020-11-02 06:38:57 45

原创 Leetcode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target (python)

题目解法:prefix+hashmap+greedy参考leetcode给的两条hint:Keep track of prefix sums to quickly look up what subarray that sums “target” can be formed at each step of scanning the input array.It can be proved that greedily forming valid subarrays as soon as one is

2020-11-02 06:30:20 22

原创 Leetcode 二分判定类题目 (python)

前言:一般求min(max)或者max(min)类题目都可以用二分判定来求解1552. Magnetic Force Between Two Balls解法:class Solution: def maxDistance(self, position: List[int], m: int) -> int: # 二分判定 # 二分搜索,每次二分到的值X,判断能不能取m个位置,这m个位置值之间两两的差绝对值的最小值大于这个X # 单次判定的

2020-11-01 05:52:33 19

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

题目解法:class Solution {public: vector<int> sortedSquares(vector<int>& A) { // get the dividing position of the negative and positive elements int n = size(A); int div_pos=0; for (int i=0;i<n;i++){

2020-10-29 13:52:33 15

原创 Leetcode 44. Wildcard Matching & Regular Expression Matching (python)

Leetcode 44. Wildcard Matching解法:动态规划这道题目在于理解代码中的step2和step4的第一部分关于step 4的第一步份,实际上可以用0,1背包跟完全背包之前的关系来理解class Solution {public: bool isMatch(string s, string p) { int sl = s.length(); int pl = p.length(); // step1:

2020-10-29 13:48:23 14

原创 Leetcode 1562. Find Latest Group of Size M (python)

Leetcode 1562. Find Latest Group of Size M题目解法1:TLE解法2:题目解法1:TLE自己开始想出来的非常复杂的解法,还是TLE了,主要T在从list里面删除元素class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: ans = -1 pos2len = {} len2pos = collections.d

2020-10-28 12:37:24 37

原创 Leetcode 1561. Maximum Number of Coins You Can Get

Leetcode 1561. Maximum Number of Coins You Can Get题目解法1:heap解法2:sort题目解法1:heap这道题的规律是,每次取剩下堆中的最大的两个值和最小的值组成triplet就可以,剩下的只是实现问题。当时自己做的时候是用一个最大堆和一个最小堆实现的,其实这样比较慢class Solution: def maxCoins(self, piles: List[int]) -> int: min_heap = pile

2020-10-28 12:24:10 30

原创 Leetcode 1560. Most Visited Sector in a Circular Track (python)

Leetcode 1560. Most Visited Sector in a Circular Track题目解法:brutal force解法2:题目解法:brutal force没有仔细思考规律就是写的这么丑陋class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: d = collections.defaultdict(int) for i in

2020-10-28 09:53:13 36

原创 Leetcode 1630. Arithmetic Subarrays (python)

Leetcode 1630. Arithmetic Subarrays题目解法1:sort解法2:利用set题目解法1:sortclass Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def check(array): array.sort() dis = a

2020-10-27 09:59:54 59

原创 Leetcode 1631 Path With Minimum Effort (python)

Leetcode Path With Minimum Effort题目解析follow up题目解析这个题目再Leetcode 的problems里面还没有,只出现在Weekly contest 212的第3题一开始觉得这个题目是个DP,觉得两遍dp可以做,实际上思路错了,两个方向的dp是不行的。基本上看到四个方向可走的题目就是用最短路径问题来做,最短路径这边也提供两种做法,一种是Bellman ford,另一种是Dijkstra,关于两种做法的详细解释看这题 Leetcode The Ma

2020-10-27 09:41:43 35

原创 Leetcode 1568. Minimum Number of Days to Disconnect Island (python)

Leetcode 1568. Minimum Number of Days to Disconnect Island题目解析:题目解析:这道题目的关键就在于,想到只有可能是0,1,2三种答案,想到了这个题目也就非常简单了class Solution: def minDays(self, grid: List[List[int]]) -> int: # check if there is more than one disconnected islands in teh

2020-10-27 07:44:44 28

原创 Leetcode 1567. Maximum Length of Subarray With Positive Product (python)

Leetcode 1567. Maximum Length of Subarray With Positive Product题目:解法1:解法2:two pass题目:解法1:这种判断正负的题目往往都是通过正负得负,负负得正这样的方式来进行交换得到的,之前也有过类似的题目:比如Leetcode 152 Maximum Product Subarray这题具体的解析如下:The main idea here is to keep a count of running positive array

2020-10-25 06:12:33 18

空空如也

空空如也

空空如也

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

TA关注的人 TA的粉丝

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