python刷题+leetcode(第三部分)
200.最大正方形
思路:與島嶼,水塘不同的是這個相對要規(guī)則得多,而不是求連通域,所以動態(tài)規(guī)劃構造出狀態(tài)轉(zhuǎn)移方程即可
動態(tài)規(guī)劃 if 0, dp[i][j] =0
if 1, dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1
class Solution:def maximalSquare(self, matrix):print('==np.array(matrix):\n', np.array(matrix))h = len(matrix)w = len(matrix[0])max_side = 0dp = [[0 for j in range(w)] for i in range(h)]print('==dp:', np.array(dp))for i in range(h):for j in range(w):if matrix[i][j] == '1' and i>0 and j>0:dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1max_side = max(max_side, dp[i][j])elif i==0:dp[i][j] = int(matrix[i][j])max_side = max(max_side, dp[i][j])elif j==0:dp[i][j] = int(matrix[i][j])max_side = max(max_side, dp[i][j])else:passprint('==dp:', np.array(dp))# print(max_side)return max_side**2matrix = [["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"], ["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"]]sol = Solution() sol.maximalSquare(matrix)201.統(tǒng)計全為 1 的正方形子矩陣
思路:動態(tài)規(guī)劃 if 0, dp[i][j] =0
if 1, dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1
為1的時候 res自加1,再加上dp[i][j]增加的部分,也可以看成是dp的和
class Solution:def countSquares(self, matrix):print('==np.array(matrix)\n', np.array(matrix))h = len(matrix)w = len(matrix[0])dp = [[0 for i in range(w)] for j in range(h)]print('==np.array(dp):', np.array(dp))res = 0for i in range(h):for j in range(w):if matrix[i][j] == 1 and i > 0 and j > 0:res += 1dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1res += dp[i][j] - 1 # 減去1代表增加的矩形個數(shù)elif i==0:dp[i][j] = matrix[i][j]if matrix[i][j] == 1:res+=1elif j==0:dp[i][j] = matrix[i][j]if matrix[i][j] == 1:res+=1else:passprint('==np.array(dp):', np.array(dp))print('==after res:', res)return resmatrix = [[0, 1, 1, 1],[1, 1, 1, 1],[0, 1, 1, 1] ] sol = Solution() sol.countSquares(matrix)202.平方數(shù)之和
思路:雙指針 左右收縮即可
class Solution:def judgeSquareSum(self, c: int) -> bool:from math import sqrtright = int(sqrt(c))left = 0while(left <= right):sum_ = left**2 + right**2if (sum_ == c):return Trueelif sum_ > c:right -= 1else:left += 1return Falsec++實現(xiàn):
?
203.分發(fā)餅干
思路:排序加貪心 先給胃口小的餅干
#思路:排序加貪心 先讓胃口小的孩子滿足 class Solution:def findContentChildren(self, g, s):print('==g:', g)print('==s:', s)g = sorted(g)#孩子s = sorted(s)#餅干res = 0for j in range(len(s)):#遍歷餅干 先給胃口小的分配if res<len(g):if g[res]<=s[j]:res+=1print('==res:', res)return resg = [1,2] s = [1,2,3] # g = [1, 2, 3] # s = [1, 1] sol = Solution() sol.findContentChildren(g, s)204.三角形最小路徑和
?思路:動態(tài)規(guī)劃
class Solution:def minimumTotal(self, triangle: List[List[int]]) -> int:for i in range(1, len(triangle)):for j in range(len(triangle[i])):if j == 0:triangle[i][j] = triangle[i-1][j] + triangle[i][j]elif j == i:triangle[i][j] = triangle[i-1][j-1] + triangle[i][j]else:triangle[i][j] = min(triangle[i-1][j-1], triangle[i-1][j]) + triangle[i][j]return min(triangle[-1])c++:
class Solution { public:int minimumTotal(vector<vector<int>>& triangle) {int h = triangle.size();for(int i = 1; i < triangle.size(); i++){for(int j = 0; j < triangle[i].size(); j++){if(j == 0){triangle[i][j] = triangle[i-1][j] + triangle[i][j];}else if(j == i){triangle[i][j] = triangle[i-1][j-1] + triangle[i][j];}else{triangle[i][j] = min(triangle[i-1][j-1], triangle[i-1][j]) + triangle[i][j];}}}return *min_element(triangle[h - 1].begin(), triangle[h - 1].end());} };205.同構字符串
思路:hash 構造映射關系
class Solution:def isIsomorphic(self, s: str, t: str) -> bool:if len(s) != len(t):return Falsedic = {}for i in range(len(s)):if s[i] not in dic:#未出現(xiàn)過if t[i] in dic.values():#value已經(jīng)出現(xiàn)過之前構造的dict中了return Falsedic[s[i]] = t[i]else:#出現(xiàn)過if dic[s[i]]!=t[i]:return Falsereturn True# s = "egg" # t = "add" s="ab" t="aa"sol = Solution() sol.isIsomorphic(s, t)206.單詞接龍 II
思路:構建圖 然后bfs
class Solution:def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:cost = {}for word in wordList:cost[word] = float("inf")cost[beginWord] = 0# print('==cost:', cost)# neighbors = collections.defaultdict(list)neighbors = {}ans = []#構建圖for word in wordList:for i in range(len(word)):key = word[:i] + "*" + word[i + 1:]if key not in neighbors:neighbors[key] = []neighbors[key].append(word)else:neighbors[key].append(word)# print('==neighbors:', neighbors)q = collections.deque([[beginWord]])# q = [[beginWord]]# print('====q:', q)#bfswhile q:# path = q.popleft()path = q.pop()# print('===path:', path)cur = path[-1]if cur == endWord:ans.append(path.copy())else:for i in range(len(cur)):new_key = cur[:i] + "*" + cur[i + 1:]if new_key not in neighbors:continuefor neighbor in neighbors[new_key]:# print('==cost[cur] + 1, cost[neighbor]:', cost[cur] + 1, cost[neighbor])if cost[cur] + 1 <= cost[neighbor]:q.append(path + [neighbor])cost[neighbor] = cost[cur] + 1# print('==ans:', ans)return ans208.最后一塊石頭的重量
思路1:while循環(huán) 排序從大到小 一直取前兩塊石頭進行比較
class Solution:def lastStoneWeight(self, stones):while len(stones)>=2:stones = sorted(stones)[::-1]if stones[0]==stones[1]:stones=stones[2:]else:stones = [stones[0]-stones[1]]+stones[2:]print('===stones:', stones)return stones[-1] if len(stones) else 0stones = [2, 7, 4, 1, 8, 1] # stones = [2, 2] sol = Solution() res= sol.lastStoneWeight(stones) print('==res:', res)更簡潔寫法:
class Solution:def lastStoneWeight(self, stones: List[int]) -> int:while len(stones) >= 2:stones = sorted(stones)stones.append(stones.pop() - stones.pop())return stones[0]思路2:堆隊列,也稱為優(yōu)先隊列
import heapq class Solution:def lastStoneWeight(self, stones):h = [-stone for stone in stones]heapq.heapify(h)print('==h:', h)while len(h) > 1:a, b = heapq.heappop(h), heapq.heappop(h)if a != b:heapq.heappush(h, a - b)print('==h:', h)return -h[0] if h else 0stones = [2, 7, 4, 1, 8, 1] # stones = [2, 2] sol = Solution() res= sol.lastStoneWeight(stones) print('==res:', res)210.無重疊區(qū)間
class Solution:def eraseOverlapIntervals(self, intervals):n = len(intervals)if n<=0:return 0intervals = sorted(intervals, key=lambda x: x[-1])print('==intervals:', intervals)res = [intervals[0]]for i in range(1, n):if intervals[i][0] >= res[-1][-1]:res.append(intervals[i])print(res)return n - len(res)# intervals = [[1, 2], [2, 3], [3, 4], [1, 3]] # intervals = [[1,100],[11,22],[1,11],[2,12]] intervals = [[0, 2], [1, 3], [2, 4], [3, 5], [4, 6]] sol = Solution() sol.eraseOverlapIntervals(intervals)212.種花問題
思路:判斷是否是1或0,1就一種情況,0有兩種情況
100 先判斷1
?01000,要判斷i為0時,i+1是否為1,否則說明就是001這種情況
# 100 先判斷1 # 01000,要判斷i為0時,i+1是否為1,否則說明就是001這種情況 class Solution:def canPlaceFlowers(self, flowerbed, n):i = 0res = 0while i<len(flowerbed):if flowerbed[i]==1:i+=2else:if i+1<len(flowerbed) and flowerbed[i+1]==1:i+=3else:res+=1i+=2return True if res>=n else False# flowerbed = [1,0,0,0,1] # n = 1# flowerbed = [1,0,0,0,1] # n = 2# flowerbed = [1,0,0,0,0,0,1] # n = 2 flowerbed = [1,0,0,0,1,0,0] n = 2 sol = Solution() res= sol.canPlaceFlowers(flowerbed, n) print('==res:', res)216.較大分組的位置
其實就是再求聚類
思路1:動態(tài)規(guī)劃
class Solution:def largeGroupPositions(self, s):dp = [0] * len(s)for i in range(1, len(s)):if s[i] == s[i - 1]:dp[i] = 1dp.append(0)print('==dp:', dp)index = [j for j in range(len(dp)) if dp[j] == 0]print('index:', index)res = []for k in range(len(index) - 1):if index[k + 1] - index[k] >= 3:res.append([index[k], index[k + 1] - 1])print('=res:', res)return ress = "abbxxxxzzy" sol = Solution() sol.largeGroupPositions(s)思路2:雙指針
# 雙指針 class Solution:def largeGroupPositions(self, s):res = []left, right = 0, 0while left < len(s):right = left + 1while right < len(s) and s[right] == s[left]:right += 1if right - left >= 3:res.append([left, right - 1])# 左指針跑到右指針位置left = rightprint('==res:', res)return ress = "abbxxxxzzy" # s = "abcdddeeeeaabbbcd" sol = Solution() sol.largeGroupPositions(s)217.省份數(shù)量
思路:
可以把 n 個城市和它們之間的相連關系看成圖, #
城市是圖中的節(jié)點,相連關系是圖中的邊,
?給定的矩陣isConnected 即為圖的鄰接矩陣,省份即為圖中的連通分量。
利用dfs將一個數(shù)組view遍歷過的城市置位1。
# dfs # 可以把 nn 個城市和它們之間的相連關系看成圖, # 城市是圖中的節(jié)點,相連關系是圖中的邊, # 給定的矩陣isConnected 即為圖的鄰接矩陣,省份即為圖中的連通分量。 class Solution:def travel(self, isConnected, i, n):self.view[i] = 1 # 表示已經(jīng)遍歷過for j in range(n):if isConnected[i][j] == 1 and not self.view[j]:self.travel(isConnected, j, n)def findCircleNum(self, isConnected):n = len(isConnected)self.view = [0] * nres = 0for i in range(n):if self.view[i] != 1:res += 1self.travel(isConnected, i, n)print('==res:', res)return res# isConnected = [[1, 1, 0], # [1, 1, 0], # [0, 0, 1]] isConnected = [[1,0,0],[0,1,0],[0,0,1]] sol = Solution() sol.findCircleNum(isConnected)218.旋轉(zhuǎn)數(shù)組
思路1:截斷拼接,注意的是一些邊界條件需要返回原數(shù)組
class Solution:def rotate(self, nums: List[int], k: int) -> None:if len(nums)<=1 or k==0 or k%len(nums)==0:return numsn = len(nums)k = k%n# print(nums[-k:]+nums[:n-k])nums[:] = nums[-k:]+nums[:n-k]return nums思路2:先左翻轉(zhuǎn),在右翻轉(zhuǎn),在整體翻轉(zhuǎn)?
class Solution:def reverse(self, i, j, nums):#交換位置的while i < j:#nums[i], nums[j] = nums[j], nums[i]i += 1j -= 1def rotate(self, nums, k):"""Do not return anything, modify nums in-place instead."""n = len(nums)k %= n #有大于n的數(shù)self.reverse(0, n - k - 1, nums) #左翻self.reverse(n - k, n - 1, nums) #右翻self.reverse(0, n - 1, nums) #整體翻print(nums)return nums# nums = [1,2,3,4,5,6,7] # k = 3 nums = [1,2,3,4,5,6] k = 11 sol = Solution() sol.rotate(nums, k)219.匯總區(qū)間
思路:雙指針
class Solution:def summaryRanges(self, nums):res = []left =0right = 0while right<len(nums):right = left+1while right<len(nums) and nums[right] - nums[right-1] == 1:right+=1if right -1>left:res.append(str(nums[left]) + "->" + str(nums[right-1]))else:res.append(str(nums[left]))left = rightprint(res)return res nums = [0,1,2,4,5,7] sol = Solution() sol.summaryRanges(nums)220.冗余連接
思路:并查集
#并查集:合并公共節(jié)點的,對相鄰節(jié)點不是公共祖先的進行合并 class Solution:def find(self, index): # 查詢if self.parent[index] == index: # 相等就返回return indexelse:return self.find(self.parent[index]) # 一直遞歸找到節(jié)點index的祖先def union(self, i, j): # 合并self.parent[self.find(i)] = self.find(j)def findRedundantConnection(self, edges):nodesCount = len(edges)self.parent = list(range(nodesCount + 1))print('==self.parent:', self.parent)for node1, node2 in edges:print('==node1, node2:', node1, node2)if self.find(node1) != self.find(node2):#相鄰的節(jié)點公共祖先不一樣就進行合并print('===hahhaha===')self.union(node1, node2)print('=self.parent:', self.parent)else:return [node1, node2]return []edges = [[1, 2], [1, 3], [2, 3]] sol = Solution() res = sol.findRedundantConnection(edges) print('=res:', res)223.可被 5 整除的二進制前綴
思路:二進制移位 在和5求余
class Solution:def prefixesDivBy5(self, A: List[int]) -> List[bool]:res = [False]*len(A)value = 0for i in range(len(A)):value = (value<<1) + A[i]# print(value)if value%5==0:res[i]=Truereturn res225.移除最多的同行或同列石頭
思路1:?其實主要是算連通域的個數(shù),當滿足同行或者同列就算聯(lián)通,
?輸出的結果就是石頭個數(shù)減去連通域個數(shù),第一種解法超時
思路2:并查集
class Solution:# 并查集查找def find(self, x):if self.parent[x] == x:return xelse:return self.find(self.parent[x])#合并def union(self,i, j):self.parent[self.find(i)] = self.find(j)def removeStones(self, stones):# 因為x,y所屬區(qū)間為[0,10^4]# n = 10001n = 10self.parent = list(range(2 * n))for i, j in stones:self.union(i, j + n)print('==self.parent:', self.parent)# 獲取連通區(qū)域的根節(jié)點res = []for i, j in stones:res.append(self.find(i))print('=res:', res)return len(stones) - len(set(res))stones = [[0, 0], [0, 1], [1, 0], [1, 2], [2, 1], [2, 2]] sol = Solution() res = sol.removeStones(stones) print('===res:', res)226..綴點成線
思路:判斷斜率 將除換成加
class Solution:def checkStraightLine(self, coordinates):n = len(coordinates)for i in range(1, n-1):if (coordinates[i+1][1]-coordinates[i][1])*(coordinates[i][0]-coordinates[i-1][0])=(coordinates[i][1]-coordinates[i-1][1])*(coordinates[i+1][0]-coordinates[i][0]):return Falsereturn Truecoordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] sol = Solution() sol.checkStraightLine(coordinates)227.賬戶合并
思路:并查集
#思想是搜索每一行的每一個郵箱,如果發(fā)現(xiàn)某一行的某個郵箱在之前行出現(xiàn)過,那么把該行的下標和之前行通過并查集來合并, class Solution(object):def find(self, x):if x == self.parents[x]:return xelse:return self.find(self.parents[x])def union(self,i, j):self.parents[self.find(i)] = self.find(j)def accountsMerge(self, accounts):# 用parents維護每一行的父親節(jié)點# 如果parents[i] == i, 表示當前節(jié)點為根節(jié)點self.parents = [i for i in range(len(accounts))]print('==self.parents:', self.parents)dict_ = {}# 如果發(fā)現(xiàn)某一行的某個郵箱在之前行出現(xiàn)過,那么把該行的index和之前行合并(union)即可for i in range(len(accounts)):for email in accounts[i][1:]:if email in dict_:self.union(dict_[email], i)else:dict_[email] = iprint('===self.parents:', self.parents)print('=== dict_:', dict_)import collectionsusers = collections.defaultdict(set)print('==users:', users)res = []# 1. users:表示每個并查集根節(jié)點的行有哪些郵箱# 2. 使用set:避免重復元素# 3. 使用defaultdict(set):不用對每個沒有出現(xiàn)過的根節(jié)點在字典里面做初始化for i in range(len(accounts)):for account in accounts[i][1:]:users[self.find(i)].add(account)print('==users:', users)# 輸出結果的時候注意結果需按照字母順序排序(雖然題目好像沒有說)for key, val in users.items():res.append([accounts[key][0]] + sorted(list(val)))return resaccounts = [["John", "johnsmith@mail.com", "john00@mail.com"],["John", "johnnybravo@mail.com"],["John", "johnsmith@mail.com", "john_newyork@mail.com"],["Mary", "mary@mail.com"]]# [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], # ["John", "johnnybravo@mail.com"], # ["Mary", "mary@mail.com"]]sol = Solution() res= sol.accountsMerge(accounts) print(res)228.連接所有點的最小費用
思路1: 其實就是求最小生成樹,首先想到的是kruskal 但是時間復雜度較高,超時
# 其實就是求最小生成樹:采用kruskal 但是時間復雜度較高,超時 class Solution:def minCostConnectPoints(self, points):edge_list = []nodes = len(points)for i in range(nodes):for j in range(i):dis = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])edge_list.append([i, j, dis])print('==edge_list:', edge_list)edge_list = sorted(edge_list, key=lambda x: x[-1])print('==edge_list:', edge_list)group = [[i] for i in range(nodes)]print('==group:', group)res = 0for edge in edge_list:for i in range(len(group)):if edge[0] in group[i]:m = i # 開始節(jié)點if edge[1] in group[i]:n = i # 結束節(jié)點if m != n:# res.append(edge)res += edge[-1]group[m] = group[m] + group[n]group[n] = []print(group)print('==res:', res)return respoints = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]] sol = Solution() sol.minCostConnectPoints(points)思路2: 其實就是求最小生成樹,首先想到的是prim 但是時間復雜度較高,超時
# prim算法 超出時間限制 class Solution:def minCostConnectPoints(self, points):# edge_list = []nodes = len(points)Matrix = [[0 for i in range(nodes)] for j in range(nodes)]for i in range(nodes):for j in range(nodes):dis = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])# edge_list.append([i, j, dis])Matrix[i][j] = dis# print('===edge_list:', edge_list)print('==Matrix:', Matrix)selected_node = [0]candidate_node = [i for i in range(1, nodes)] # 候選節(jié)點print('==candidate_node:', candidate_node)# res = []res = 0while len(candidate_node):begin, end, minweight = 0, 0, float('inf')for i in selected_node:for j in candidate_node:if Matrix[i][j] < minweight:minweight = Matrix[i][j]begin = i # 存儲開始節(jié)點end = j # 存儲終止節(jié)點# res.append([begin, end, minweight])print('==end:', end)res += minweightselected_node.append(end) # 找到權重最小的邊 加入可選節(jié)點candidate_node.remove(end) # 候選節(jié)點被找到 進行移除print('==res:', res)return respoints = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]] # points = [[-1000000, -1000000], [1000000, 1000000]] sol = Solution() sol.minCostConnectPoints(points)思路3:并查集
class Solution:def find(self, x):if self.parents[x] == x:return xelse:return self.find(self.parents[x]) # 一直找到幫主def union(self, i, j): # 替換為幫主 站隊self.parents[self.find(i)] = self.find(j)def minCostConnectPoints(self, points):costs_list = []n = len(points)for i in range(n):for j in range(i + 1, n):dis = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])costs_list.append([dis, i, j])# print('==costs_list:', costs_list)costs_list = sorted(costs_list, key=lambda x: x[0])print('==costs_list:', costs_list)self.parents = [i for i in range(n)]print('==init self.parents:', self.parents)res = 0for i in range(len(costs_list)):dis, x, y = costs_list[i]if self.find(x) != self.find(y):self.union(x, y)print('==x,y:', x, y)print('==self.parents:', self.parents)res += disprint('==res:', res)return respoints = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]] sol = Solution() sol.minCostConnectPoints(points)229.正則表達式匹配
思路:字符串的匹配問題,自然想到用dp,做成二維矩陣方便進行狀態(tài)方程的轉(zhuǎn)移
f[i][j]:s的前i個字符和p的前j個字符是否相等
p的第j個字符是字母:p[j]==s[i]時 ,f[i][j]=f[i-1][j-1]
p的第j個字符是字母:p[j]!=s[i]時 ,f[i][j]=False
p的第j個字符是*:s[i]==p[j-1],f[i][j]=f[i-1][j] or f[i][j-2]
p的第j個字符是*:s[i]!=p[j-1],f[i][j]=f[i][j-2]
230.最長回文子串
思路:中心枚舉,雙指針,需要注意的是有上述兩種情況,左右指針的索引有兩種
class Solution:def help(self, left, right, s, n):while left >= 0 and right < n:if s[left] == s[right]:left -= 1right += 1else:breaktemp = s[left+1:right]self.res = max(self.res, temp, key=len)def longestPalindrome(self, s):self.res = s[0]n = len(s)for i in range(1, n):self.help(i-1, i+1, s, n)#針對"babad"self.help(i - 1, i, s, n)#針對"cbbd"print('==self.res:', self.res)return self.res# s = "babad" s = "cbbd" sol = Solution() sol.longestPalindrome(s)231.尋找兩個正序數(shù)組的中位數(shù)
思路:雙指針,走完剩下的在進行合并
class Solution:def findMedianSortedArrays(self, nums1, nums2):res = []i, j = 0, 0m, n = len(nums1), len(nums2)while i < m and j < n:if nums1[i] < nums2[j]:res.append(nums1[i])i += 1else:res.append(nums2[j])j += 1print('==res:', res)print('==i:', i)print('==j:', j)if i < m:res.extend(nums1[i:])if j < n:res.extend(nums2[j:])print('==res:', res)if (m+n)%2==0:#偶數(shù)return (res[(m+n)//2]+res[(m+n)//2-1])/2else:#奇數(shù)return res[(m+n)//2]# nums1 = [1, 1, 3] # nums2 = [2] nums1 = [1,2] nums2 = [3,4] sol = Solution() res = sol.findMedianSortedArrays(nums1, nums2) print(res)232.連通網(wǎng)絡的操作次數(shù)
思路:并查集 其實就是求當前的聯(lián)通量個數(shù)減去一個聯(lián)通量的值,對于n個節(jié)點,要給n-1條邊才會滿足都能連上,采用并查集去做聚類,否則就不滿足了
class Solution:def find(self, x):if x==self.parent[x]:return xelse:return self.find(self.parent[x])def union(self,x,y):#將x的老大換成y的老大self.parent[self.find(x)] = self.find(y)def makeConnected(self, n, connections):if len(connections) < n - 1:return -1self.parent = [i for i in range(n)]clusters = nfor connection in connections:x, y = connectionif self.find(x)!=self.find(y):clusters-=1self.union(x, y)print('==x,y', x, y)print('==self.parent:', self.parent)print(clusters)return clusters-1n = 4 connections = [[0,1],[0,2],[1,2]] sol = Solution() sol.makeConnected(n, connections)234.最長連續(xù)遞增序列
思路:棧
class Solution:def findLengthOfLCIS(self, nums):stack = []res = 0for i in range(len(nums)):if stack and nums[i]<=stack[-1]:stack=[]stack.append(nums[i])res = max(len(stack), res)# print('==stack:', stack)# print(res)return res nums = [1, 3, 5, 4, 7] sol = Solution() sol.findLengthOfLCIS(nums)235.由斜杠劃分區(qū)域
思路;把斜線換成3*3網(wǎng)格,就變成水域問題了
import numpy as npclass Solution:def dfs(self, i, j, h, w, matrix):if i < 0 or j < 0 or i >= h or j >= w or matrix[i][j] != 0:returnmatrix[i][j] = -1self.dfs(i - 1, j, h, w, matrix)self.dfs(i, j - 1, h, w, matrix)self.dfs(i + 1, j, h, w, matrix)self.dfs(i, j + 1, h, w, matrix)def regionsBySlashes(self, grid):n = len(grid)matrix = [[0 for _ in range(3 * n)] for _ in range(3 * n)]print(np.array(matrix))for i in range(n):for j in range(len(grid[i])):if grid[i][j] == '/':matrix[i * 3][j * 3 + 2] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3 + 2][j * 3] = 1elif grid[i][j] == '\\':matrix[i * 3 + 2][j * 3 + 2] = matrix[i * 3 + 1][j * 3 + 1] = matrix[i * 3][j * 3] = 1print(np.array(matrix))res = 0for i in range(3 * n):for j in range(3 * n):if matrix[i][j] == 0:res+=1self.dfs(i, j, 3 * n, 3 * n, matrix)print('==res:', res)return res# grid = [" /", "/ "] grid = ["/\\", "/\\"] sol = Solution() sol.regionsBySlashes(grid)要注意的是如果格子用2*2,會出現(xiàn)這種0不會挨著的,會出錯
236.等價多米諾骨牌對的數(shù)量
思路1;
兩層循環(huán) 超時
class Solution:def numEquivDominoPairs(self, dominoes):#兩層循環(huán) 超時n = len(dominoes)left, right = 0, 0res=0while left<n:right=left+1while right<n:if dominoes[right]==dominoes[left][::-1] or dominoes[right]==dominoes[left]:res+=1right+=1left+=1print('==res:', res)return res思路2:做成字典,記錄相同的個數(shù),兩兩之間相互組合為n*(n-1)/2
class Solution:def numEquivDominoPairs(self, dominoes):# 字典法ans = 0dict_ = {}for d1, d2 in dominoes:# 排序后加入字典index = tuple(sorted((d1, d2)))if index in dict_:dict_[index] += 1else:dict_[index] = 1print('==dict_:', dict_)# 計算答案for i in dict_:#n*n(-1)/2ans += dict_[i] * (dict_[i] - 1) // 2return ans思路3:桶計數(shù),兩兩之間相互組合為n*(n-1)/2
class Solution:def numEquivDominoPairs(self, dominoes): #桶裝法nums = [0]*100res = 0for dominoe in dominoes:x,y = dominoeif x>y:nums[x*10+y] +=1else:nums[y * 10 + x] += 1for num in nums:if num>=2:res += num*(num-1)//2print(res)return res239.尋找數(shù)組的中心索引
class Solution:def pivotIndex(self, nums):n = len(nums)for i in range(n):left_sum = sum(nums[:i])right_sum = sum(nums[i+1:])if left_sum == right_sum:return ireturn -1nums = [1, 7, 3, 6, 5, 6] sol = Solution() res = sol.pivotIndex(nums) print(res)240.最小體力消耗路徑
思路1:咋一眼看過去,以為直接用dp就行,但是真正在寫的過程中,發(fā)現(xiàn)消耗的最小體力沒有狀態(tài)轉(zhuǎn)移方程,所以可不可以看成先初始化給一個體力值,如果能達到右下腳,將體力值減少,而這個減少的過程采用二分法這樣減少更快
代碼注釋的部分使用list會超時,換成集合就好了,不會超時
# 思路:二分法,先給定一個初始體力值,能夠走到的話,就減少體力,否則增加體力 class Solution:def minimumEffortPath(self, heights):h, w = len(heights), len(heights[0])left_value, right_value, res = 0, 10 ** 6 - 1, 0# 二分法while left_value <= right_value: # 終止條件 找到合適的體力值mid = left_value + (right_value - left_value) // 2# start_point = [[0, 0]]# seen = [[0, 0]]start_point = [(0, 0)]seen = {(0, 0)}while start_point:x, y = start_point.pop(0)for x_, y_ in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:# 不超過范圍 也沒見過 差值也小與給定的體力值# if 0 <= x_ < h and 0 <= y_ < w and [x_, y_] not in seen and abs(# heights[x][y] - heights[x_][y_]) <= mid:# start_point.append([x_, y_])# seen.append([x_, y_])if 0 <= x_ < h and 0 <= y_ < w and (x_, y_) not in seen and abs(heights[x][y] - heights[x_][y_]) <= mid:start_point.append((x_, y_))seen.add((x_, y_))print('==seen:', seen)if (h - 1, w - 1) in seen: # 足夠到底右下角,說明體力足夠,那么繼續(xù)減少體力res = midright_value = mid - 1else: # 到不了右下角,說明體力不夠,需要增加體力left_value = mid + 1return resheights = [[1, 2, 2],[3, 8, 2],[5, 3, 5]] sol = Solution() res = sol.minimumEffortPath(heights) print('==res:', res)思路2:并查集
將節(jié)點與節(jié)點之間的邊與權重構建出來
按權重從小到大 不斷合并 只要出現(xiàn)從起始點到終止點能夠到達 說明找到了 此時的值就是最大消耗體力值
241.不用加減乘除做加法
思路:分為進位和 當前位的異或
class Solution:def add(self, a: int, b: int) -> int:add_flag = (a&b)<<1;#進位在左移sum_ = a^b;#異或 取值 相同為0 不同為1return sum_+add_flag242.水位上升的泳池中游泳
堆隊列 也稱為優(yōu)先隊列 就是根節(jié)點的值最小
思路:采用bfs + 堆隊列? 保證能到達左下角的時候 需要最小的時間
# 堆隊列 也稱為優(yōu)先隊列 就是根節(jié)點的值最小 # 思路:采用dfs + 堆隊列 import heapqclass Solution:def swimInWater(self, grid):h, w = len(grid), len(grid[0])res = 0heap = [(grid[0][0], 0, 0)]visited = {(0, 0)}while heap:print('===heap:', heap)height, x, y = heapq.heappop(heap)res = max(res, height)if x == w - 1 and y == h - 1:return resfor dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)):new_x, new_y = x + dx, y + dyif 0 <= new_x < w and 0 <= new_y < h and (new_x, new_y) not in visited:visited.add((new_x, new_y))heapq.heappush(heap, (grid[new_x][new_y], new_x, new_y))return -1grid = [[0, 2],[1, 3]] # grid = [[0, 1, 2, 3, 4], # [24, 23, 22, 21, 5], # [12, 13, 14, 15, 16], # [11, 17, 18, 19, 20], # [10, 9, 8, 7, 6]] sol = Solution() sol.swimInWater(grid)243.從相鄰元素對還原數(shù)組
思路:構建字典,進行bfs遍歷 依次對出現(xiàn)過一次的字符 添加進列表即可
#bfs class Solution():def restoreArray(self, adjacentPairs):""":type adjacentPairs: List[List[int]]:rtype: List[int]"""import collectionsmemory = collections.defaultdict(list)for x,y in adjacentPairs:memory[x].append(y)memory[y].append(x)print('==memory:', memory)res = []visited = set()queue = []for key, value in memory.items():if len(value) == 1:queue.append((key, value[0]))while queue:print('==queue:', queue)start, end = queue.pop()res.append(start)print('==res:', res)visited.add(start)for num in memory[end]:if num in visited:continuequeue.append((end, num))return resadjacentPairs = [[2,1],[3,4],[3,2]] # # adjacentPairs = [[4,-2], # # [1,4], # # [-3,1]] # # adjacentPairs = [[100000,-100000]] # adjacentPairs =[[4,-10], # [-1,3], # [4,-3], # [-3,3]] sol = Solution() ress= sol.restoreArray(adjacentPairs) print(ress)246.公平的糖果棒交換
#思路1:兩層for循環(huán) 超時
#思路1:兩層for循環(huán) 超時 class Solution:def fairCandySwap(self, A, B):sum_A = sum(A)sum_B = sum(B)target = (sum_A+sum_B)//2for i in range(len(A)):for j in range(len(B)):if sum(A[:i])+sum(A[i+1:])+B[j] == target:return [A[i], B[j]]return []# A = [1, 2] # B = [2, 3] A = [1 ,2, 5] B = [2, 4] sol = Solution() res = sol.fairCandySwap(A, B) print(res)?思路2:雙指針 利用?sumA-x+y = sumB+x-y -->(sumA-sumB)/2 = x-y? 轉(zhuǎn)換為尋找兩個元素
#思路1:#sumA-x+y = sumB+x-y -->(sumA-sumB)/2 = x-y # 故用雙指針 轉(zhuǎn)換為二分查找 去查找兩數(shù)之差 class Solution:def fairCandySwap(self, A, B):i = 0j = 0A = sorted(A)B = sorted(B)sum_A = sum(A)sum_B = sum(B)target = (sum_A-sum_B)/2print('==target:', target)while i<len(A) and j<len(B):if (A[i] - B[j]) == target:return [A[i], B[j]]elif (A[i] - B[j])>target:j+=1else:i+=1return []# A = [1, 2] # B = [2, 3] A = [1,2,5] B = [2,4] sol = Solution() res = sol.fairCandySwap(A, B) print(res)思路3:一層for循環(huán)?利用?sumA-x+y = sumB+x-y -->(sumA-sumB)/2 = x-y? 轉(zhuǎn)換為尋找兩個元素
#思路2:#sumA-x+y = sumB+x-y -->(sumA-sumB)/2 = x-y # 一層for循環(huán)走遍 class Solution:def fairCandySwap(self, A, B):sum_A = sum(A)sum_B = sum(B)target = (sum_A-sum_B)//2for num in B:if num+target in A:return [num+target, num]return []A = [1, 2] B = [2, 3] # A = [1 ,2, 5] # B = [2, 4] sol = Solution() res = sol.fairCandySwap(A, B) print(res)247.替換后的最長重復字符
思路:如果k==0其實就是求最長字符串 ,k大于0,那么采用滑動窗口的方式 對左右指針求最少字符(也可能是不同字符)個數(shù)
如果最少字符個數(shù)大于k說明 左指針該右移動了,否則右指針一直在右移
# 思路:如果k==0其實就是求最長字符串 ,k大于0,那么采用滑動窗口的方式 對左右指針求最少字符個數(shù) # 如果最少字符個數(shù)大于k說明 左指針改右移動了,否則右指針一直在右移 class Solution:def characterReplacement(self, s, k):left, right = 0, 0nums = [0] * 26# max_num = 0res = 0while right < len(s):nums[ord(s[right]) - ord('A')] += 1max_num = max(nums)#減去max_num 就是 求左右指針內(nèi)最少字符(也可能是不同字符)個數(shù)while right - left + 1 - max_num > k:nums[ord(s[left]) - ord('A')] -= 1left += 1right += 1res = max(right - left, res)print('==res:', res)return res# s = "ABAB" # k = 2 s = "AABABBA" k = 1 sol = Solution() res = sol.characterReplacement(s, k) print('==res:', res)250.子數(shù)組最大平均數(shù) I
思路1:采用list和 ,超時
class Solution:def findMaxAverage(self, nums, k):res = float('-inf')for i in range(len(nums)-k+1):res = max(sum(nums[i:i+k]), res)print(res)return res/knums = [1, 12, -5, -6, 50, 3] k = 4 sol = Solution() sol.findMaxAverage(nums, k)思路2:采用前綴和,空間換時間
class Solution:def findMaxAverage(self, nums, k):length =len(nums)pre_sum = [0]*lengthpre_sum[0] = nums[0]for i in range(1, length):pre_sum[i] = pre_sum[i-1]+nums[i]print('===pre_sum:', pre_sum)res = float('-inf')for i in range(k-1, length):if i > k-1:res = max(res, pre_sum[i] - pre_sum[i-k])else:res = pre_sum[i]print('==res:', res)return res/knums = [1, 12, -5, -6, 50, 3] k = 4 sol = Solution() res = sol.findMaxAverage(nums, k) print('==res:', res)思路3:雙指針
class Solution:def findMaxAverage(self, nums, k):length = len(nums)Sum = 0res = float('-inf')left,right=0,0while right<length:Sum += nums[right]if right>=k-1:res =max(res, Sum)print('==res:', res)Sum-=nums[left]left += 1right+=1return res/knums = [1, 12, -5, -6, 50, 3] k = 4 sol = Solution() res = sol.findMaxAverage(nums, k) print('==res:', res)251.盡可能使字符串相等
思路;轉(zhuǎn)換成距離列表后進行雙指針滑動窗口即可
#雙指針 class Solution:def equalSubstring(self, s, t, maxCost):length = len(s)dist_cost = [0] * lengthfor i in range(length):dist_cost[i] = abs(ord(s[i]) - ord(t[i]))print('==dist_cost:', dist_cost)res = 0left,right =0,0Sum = 0while right<length:Sum+=dist_cost[right]if Sum>maxCost:Sum -= dist_cost[left]left+=1right+=1res = max(res, right - left)print(res)return res # s = "abcd" # t = "bcdf" # cost = 3 # s = "abcd" # t = "acde" # cost = 0 s = "krrgw" t = "zjxss" cost = 19 # s = "abcd" # t = "cdef" # cost = 3 sol = Solution() sol.equalSubstring(s, t, cost)261.可獲得的最大點數(shù)
思路:轉(zhuǎn)換為求連續(xù)的和最小, 那么自然用滑動窗口解決即可以
class Solution:def maxScore(self, cardPoints, k):length = len(cardPoints)leaving_k = length - kprint('==leaving_k:', leaving_k)if leaving_k == 0:return sum(cardPoints)left, right = 0, 0min_res = float('inf')temp_res = 0while right < length:temp_res += cardPoints[right]if right >= leaving_k - 1:min_res = min(min_res, temp_res)print('==temp_res:', temp_res)left += 1temp_res -= cardPoints[left - 1]right += 1print('==min_res:', min_res)return sum(cardPoints) - min_rescardPoints = [1, 2, 3, 4, 5, 6, 1] k = 3 # cardPoints = [9, 7, 7, 9, 7, 7, 9] # k = 7 sol = Solution() sol.maxScore(cardPoints, k)262.非遞減數(shù)列
思路:分別從左右兩邊判斷是否遞增
class Solution:def checkPossibility(self, nums: List[int]) -> bool:length = len(nums)# res = 0left,right = 0,length-1while left<length-1 and nums[left]<=nums[left+1]:left+=1if left==length-1:return Truewhile right>=0 and nums[right-1]<=nums[right]:right-=1if right - left>1:return Falseif left==0 or right==length-1:return Trueif nums[right+1]>=nums[left] or nums[left-1]<=nums[right]:return Truereturn False264.最長湍流子數(shù)組
思路:雙指針
滿足山峰:arr[right]>arr[right-1] and arr[right]>arr[right+1]? right+=1
滿足山谷:arr[right]
其他時候 left移動到right位置
class Solution:def maxTurbulenceSize(self, arr):left, right = 0, 0length = len(arr)res = 1while right<length-1:if left==right:if left+1<length and arr[left]==arr[left+1]:left+=1right+=1else:#山峰if right+1<length and arr[right]>arr[right-1] and arr[right]>arr[right+1]:right+=1# 山谷elif right+1<length and arr[right]<arr[right-1] and arr[right]<arr[right+1]:right+=1else:left=rightprint('==right:', right)res = max(res, right-left+1)print('==res:', res)return res# arr = [9,4,2,10,7,8,8,1,9] # arr = [100] arr = [2,1] sol = Solution() sol.maxTurbulenceSize(arr)
267.數(shù)據(jù)流中的第 K 大元素
思路1:每個add進去 就sort取第k大,時間復雜度偏大k*log(k),對于這種取topk問題,用最小堆更合適
#k*O(logk) 超時 class KthLargest:def __init__(self, k, nums):self.k = kself.nums = numsdef add(self, val):self.nums.append(val)self.nums = sorted(self.nums)[::-1]return self.nums[self.k - 1] k = 3 nums = [4, 5, 8, 2] sol = KthLargest(k, nums) res = sol.add(3) print('=res:', res) res = sol.add(5) print('=res:', res) res = sol.add(10) print('=res:', res) res = sol.add(9) print('=res:', res) res = sol.add(4) print('=res:', res)思路2:最小堆,保證最小堆中只有k個元素,那么堆頂自然就是第k大元素
時間復雜度為log(k),因為push和pop都是log(k).
python代碼
# 最小堆 topk都用最小堆 import heapq class KthLargest(object):def __init__(self, k, nums):""":type k: int:type nums: List[int]"""self.k = kself.que = numsheapq.heapify(self.que)def add(self, val):""":type val: int:rtype: int"""heapq.heappush(self.que, val)print('=====self.que====:', self.que)while len(self.que)>self.k:#保持最小堆中只有k個元素 則堆頂就是第k大元素heapq.heappop(self.que)print('clean self.que:', self.que)return self.que[0]k = 3 nums = [4, 5, 8, 2] sol = KthLargest(k, nums) res = sol.add(3) print('=res:', res) res = sol.add(5) print('=res:', res)c++代碼:
#include <map> #include <vector> #include <iostream> #include <queue> using namespace std;class KthLargest { public:priority_queue<int, vector<int>, greater<int> > que;//最小堆int k;KthLargest(int k, vector<int>& nums) {this->k = k;for(int k=0;k<nums.size();k++){que.push(nums[k]);if (que.size()>this->k){que.pop();}}}int add(int val) {que.push(val);if(que.size()>this->k){que.pop();}return que.top();} };int main() { int k=3;vector<int> nums;nums={4,5,8,2};KthLargest *p = new KthLargest(k, nums);int res = p->add(3);cout<<"res:"<<res<<endl;res = p->add(5);cout<<"res:"<<res<<endl;res = p->add(10);cout<<"res:"<<res<<endl;res = p->add(9);cout<<"res:"<<res<<endl;res = p->add(4);cout<<"res:"<<res<<endl;delete p;p=NULL;return 0;}269.楊輝三角 II
思路:一層一層遍歷出值即可
python代碼:
class Solution:def getRow(self, rowIndex: int) -> List[int]:temp = [0]*(rowIndex+1)temp[0] = 1for i in range(1, rowIndex+1):for j in range(i, 0, -1):temp[j] += temp[j-1]# print('==temp:', temp)return tempc++代碼:
#include <map> #include <vector> #include <iostream> #include <queue> #include <algorithm> using namespace std; class Solution { public:vector<int> getRow(int rowIndex) {vector<int> temp(rowIndex+1, 0);temp[0] = 1;for (int i=1;i<rowIndex+1;i++){for(int j=i;j>0;j--){temp[j]+=temp[j-1];} }return temp;} };int main() { Solution *p = new Solution();int row_index = 3;vector <int> res;res = p->getRow(row_index);for(int k=0;k<res.size();k++){cout<<"res[k]"<<res[k]<<endl;}p=NULL;delete p;return 0; }271.找到所有數(shù)組中消失的數(shù)字
思路1:hash??空間復雜度 o(n) 時間復雜度o(n)
# 空間復雜度 o(n) 時間復雜度o(n) class Solution:def findDisappearedNumbers(self, nums):dict_={}for i in range(len(nums)):dict_[nums[i]] = dict_.get(nums[i],0)+1res = []for i in range(len(nums)):if i+1 not in dict_:res.append(i+1)print(res)return res思路2:求出索引在對應位置處 添加長度 如果沒有的數(shù)字,則數(shù)字就小于等于長度
空間復雜度O(1) 時間復雜度O(n)
#空間復雜度O(1) 時間復雜度O(n) class Solution:def findDisappearedNumbers(self, nums):length = len(nums)for i in range(len(nums)):index= (nums[i]-1)%lengthnums[index] +=lengthprint('==nums:', nums)res = [i+1 for i in range(length) if nums[i] <= length]print(res)return res# nums = [4,3,2,7,8,2,3,1] nums = [1,2,2,3,3,4,7,8] # nums = [1,2,3,3,5,6,7] sol = Solution() sol.findDisappearedNumbers(nums)c++代碼:
#include <map> #include <vector> #include <iostream> #include <queue> #include <string> #include <algorithm> using namespace std; class Solution { public:vector<int> findDisappearedNumbers(vector<int>& nums) {vector<int> res;for (int i=0;i<nums.size();i++){int index = (nums[i]-1)%nums.size();nums[index] += nums.size();}for (int i=0;i<nums.size();i++){if(nums[i]<=nums.size()){res.push_back(i+1);}}return res;} };int main() {Solution *p = new Solution();vector <int >nums;nums = {4,3,2,7,8,2,3,1};vector <int> res = p->findDisappearedNumbers(nums);for(int i=0;i<res.size();i++){cout<<"res:"<<res[i]<<endl; }delete p;p = NULL;return 0; }?272.情侶牽手
思路:其實就是將環(huán)拆開,0,1都看成第0對,2,3看成第1對
可看出要交換的座位就是環(huán)的邊數(shù)減去1,對于這種去環(huán)問題,自然想到并查集
python代碼:
class Solution:def find(self,x):if self.parent[x]==x:return xreturn self.find(self.parent[x])def union(self,i,j):#將i的老大變成j的老大self.parent[self.find(i)] = self.find(j)def get_count(self,n):for i in range(n):self.count[self.find(i)]+=1def minSwapsCouples(self, row):n = len(row)//2self.parent = [i for i in range(n)]self.count = [0 for i in range(n)]print('===init self.parent', self.parent)for i in range(0, len(row), 2):self.union(row[i]//2, row[i+1]//2)print('==self.parent:', self.parent)self.get_count(n)print('===self.count:', self.count)res = 0for i in range(n):res += max(self.count[i]-1, 0)print(res)return res# row = [0,2,2] # row = [0, 2, 1, 3] # row = [2,0,5,4,3,1] row = [1,4,0,5,8,7,6,3,2,9] # row = [0, 1, 2, 3] sol = Solution() sol.minSwapsCouples(row)c++代碼:
#include <map> #include <vector> #include <iostream> #include <queue> #include <string> #include <algorithm> using namespace std;class Solution { public:vector<int> parent;vector<int> count;int find(int x){if(x==parent[x]){return x;}return find(parent[x]);}//把i的老大換成j的老大void merge(int i, int j){parent[find(i)]=find(j);}void get_count(int n){for (int i=0;i<n;i++){ count[find(i)]+=1;}}int minSwapsCouples(vector<int>& row) {int n = row.size()/2;cout<<n<<endl;int res=0;for(int i=0;i<n;i++){parent.push_back(i);count.push_back(0);}for(int i=0;i<row.size();i+=2){merge(row[i]/2,row[i+1]/2);}get_count(n);// // //debug // for (int i=0;i<parent.size();i++)// {// cout<<"===parent[i]"<<parent[i]<<endl;// }//debug // for (int i=0;i<count.size();i++)// {// cout<<"===count[i]"<<count[i]<<endl;// }for (int i=0;i<count.size();i++){res+=max(count[i]-1,0);}return res;} }; int main() {Solution *p = new Solution();vector<int> row;row = {0, 2, 1, 3};int res = p->minSwapsCouples(row);cout<<"==res:"<<res<<endl;delete p;p=NULL;return 0; }273.最大連續(xù)1的個數(shù)
思路1:直接數(shù)1個數(shù)
class Solution:def findMaxConsecutiveOnes(self, nums):count_one = 0res = 0for i in range(len(nums)):if nums[i]==1:count_one+=1else:count_one=0res = max(res, count_one)# print(res)return res思路2:dp
class Solution:def findMaxConsecutiveOnes(self, nums):res = [-1]for i in range(len(nums)):if nums[i]==0:res.append(i)res.append(len(nums))print(res)if len(res)==1:return res[-1]max_length = 0for i in range(1, len(res)):max_length = max(res[i]-res[i-1]-1, max_length)print(max_length)return max_length思路3:雙指針滑動窗口
class Solution:def findMaxConsecutiveOnes(self, nums):left,right=0,0res = 0while right<len(nums):if nums[right]==1:right+=1else:right+=1left=rightprint('==left,right:', left, right)res = max(res, right - left)print('==res:', res)return resc++雙指針:
#include <vector> #include <iostream> #include <string> #include <algorithm> using namespace std;class Solution { public:int findMaxConsecutiveOnes(vector<int>& nums) {int left=0;int right = 0;int res = 0;while (right<nums.size()){if(nums[right]==1){right++;}else{ right++;left=right; }res = max(right-left, res);}return res; } };int main() {Solution *p = new Solution();vector<int> nums;nums = {1,1,0,1,1,1};int res = p->findMaxConsecutiveOnes(nums);cout<<"==res:"<<res<<endl;delete p;p=NULL;return 0; }274.重塑矩陣
思路:對于h*w的元素個數(shù),索引為h_index = i//rows,w_index = i%rows
python代碼
class Solution:def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:h = len(nums)w = len(nums[0])if h*w != r*c:return numsres = [[0 for _ in range(c)] for _ in range(r)]# print(res)for i in range(h*w):res[i//c][i%c] = nums[i//w][i%w]# print(res)return resc++代碼:
class Solution { public:vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {int h = nums.size();int w = nums[0].size();// cout<<"==h:"<<h<<endl;vector<vector<int>> res(r ,vector<int>(c,0)); //初始化c*r元素為0的矩陣 // cout<<"==res.size():"<<res.size()<<endl;// cout<<"==res[0].size():"<<res[0].size()<<endl;if(h*w!=r*c){return nums;}for (int i=0;i<h*w;i++){ // cout<<"i/w:"<<i/w<<endl;// cout<<"i%w:"<<i%w<<endl;res[i/c][i%c] = nums[i/w][i%w];}return res;} };275.最大連續(xù)1的個數(shù) III
思路:其實就是滑動窗口判斷有大于K個0的則左指針右移動,之所以用大于K來判斷是因為0后續(xù)可能會跟著很多1,所以大于K的話,會把這些包含進去,和https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/?思想一樣
python:
class Solution:def longestOnes(self, A: List[int], K: int) -> int:left,right =0,0n = len(A)zero_count =0res = 0while right<n:if A[right]==0:zero_count+=1#left向右收縮while zero_count>K:#大于K個0的時候就說明找到符合條件的了if A[left]==0:zero_count-=1left+=1res = max(res, right - left + 1)# print('=left:', left)# print('==right:', right)# print('==res:', res)right+=1# print(res)return resc++
class Solution { public:int longestOnes(vector<int>& A, int K) {int left=0;int right =0;int res=0;int zero_count =0;int length = A.size();while(right<length){ if (A[right]==0){zero_count++;}while (zero_count>K){ if (A[left]==0){zero_count--;}left++;}res = max(res, right-left+1);right++;}return res;} };276.數(shù)組的度
思路:三個hash,一個計度,一個記錄左索引,一個記錄右索引
python:
class Solution:def findShortestSubArray(self, nums: List[int]) -> int:dict_ = {}left_index_dict = {}right_index_dict = {}for i in range(len(nums)):dict_[nums[i]] = dict_.get(nums[i], 0)+1if nums[i] not in left_index_dict:left_index_dict[nums[i]] = iright_index_dict[nums[i]] = i# print('==dict_:', dict_)# print('=left_index_dict:', left_index_dict)# print('==right_index_dict:', right_index_dict)dict_ = dict(sorted(dict_.items(), key=lambda x:x[1],reverse=True))# print(dict_)max_degree = 0res = float('inf')for key,value in dict_.items():max_degree = valuebreak# print(max_degree)for key, value in dict_.items():if value==max_degree:res = min(res, right_index_dict[key] - left_index_dict[key]+1)# print('===res:',res)return resc++:
class Solution { public:int findShortestSubArray(vector<int>& nums) {map<int, int>dict_;map<int, int>left_index_dict;map<int, int>right_index_dict;for(int i=0;i<nums.size();i++){dict_[nums[i]]++;if(left_index_dict.count(nums[i])==0){left_index_dict[nums[i]] = i;}right_index_dict[nums[i]] = i;}int max_degree=0;map<int,int>::iterator iter=dict_.begin();for (;iter!=dict_.end();iter++){max_degree = max(max_degree, iter->second);}int res=INT_MAX;map<int,int>::iterator iter_2=dict_.begin();for (;iter_2!=dict_.end();iter_2++){if (max_degree == iter_2->second){res = min(res, right_index_dict[iter_2->first] - left_index_dict[iter_2->first]+1);}}return res;} };總結
以上是生活随笔為你收集整理的python刷题+leetcode(第三部分)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数字图像处理 第二章 图像处理基础
- 下一篇: C++开源项目