Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1ba7c0f

Browse files
committed
keeping originals
1 parent93c6a9b commit1ba7c0f

File tree

177 files changed

+3667
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

177 files changed

+3667
-0
lines changed

‎1-Two-Sum.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
classSolution:
2+
deftwoSum(self,nums:List[int],target:int)->List[int]:
3+
prevMap= {}# val -> index
4+
5+
fori,ninenumerate(nums):
6+
diff=target-n
7+
ifdiffinprevMap:
8+
return [prevMap[diff],i]
9+
prevMap[n]=i

‎10-Regular-Expression-Matching.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# BOTTOM-UP Dynamic Programming
2+
classSolution:
3+
defisMatch(self,s:str,p:str)->bool:
4+
cache= [[False]* (len(p)+1)foriinrange(len(s)+1)]
5+
cache[len(s)][len(p)]=True
6+
7+
foriinrange(len(s),-1,-1):
8+
forjinrange(len(p)-1,-1 ,-1):
9+
match=i<len(s)and (s[i]==p[j]orp[j]==".")
10+
11+
if (j+1)<len(p)andp[j+1]=="*":
12+
cache[i][j]=cache[i][j+2]
13+
ifmatch:
14+
cache[i][j]=cache[i+1][j]orcache[i][j]
15+
elifmatch:
16+
cache[i][j]=cache[i+1][j+1]
17+
18+
returncache[0][0]
19+
20+
21+
# TOP DOWN MEMOIZATION
22+
classSolution:
23+
defisMatch(self,s:str,p:str)->bool:
24+
cache= {}
25+
26+
defdfs(i,j):
27+
if (i,j)incache:
28+
returncache[(i,j)]
29+
ifi>=len(s)andj>=len(p):
30+
returnTrue
31+
ifj>=len(p):
32+
returnFalse
33+
34+
match=i<len(s)and (s[i]==p[j]orp[j]==".")
35+
if (j+1)<len(p)andp[j+1]=="*":
36+
cache[(i,j)]= (dfs(i,j+2)or# dont use *
37+
(matchanddfs(i+1,j)))# use *
38+
returncache[(i,j)]
39+
ifmatch:
40+
cache[(i,j)]=dfs(i+1,j+1)
41+
returncache[(i,j)]
42+
cache[(i,j)]=False
43+
returnFalse
44+
45+
returndfs(0,0)

‎100-Same-Tree.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
classSolution:
9+
defisSameTree(self,p:TreeNode,q:TreeNode)->bool:
10+
ifnotpandnotq:returnTrue
11+
ifpandqandp.val==q.val:
12+
returnself.isSameTree(p.left,q.left)andself.isSameTree(p.right,q.right)
13+
else:returnFalse
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
classSolution:
9+
deflevelOrder(self,root:TreeNode)->List[List[int]]:
10+
res= []
11+
q=collections.deque()
12+
ifroot:q.append(root)
13+
14+
whileq:
15+
val= []
16+
17+
foriinrange(len(q)):
18+
node=q.popleft()
19+
val.append(node.val)
20+
ifnode.left:q.append(node.left)
21+
ifnode.right:q.append(node.right)
22+
res.append(val)
23+
returnres

‎104-Maximum-Depth-of-Binary-Tree.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# RECURSIVE DFS
2+
classSolution:
3+
defmaxDepth(self,root:TreeNode)->int:
4+
ifnotroot:
5+
return0
6+
7+
return1+max(self.maxDepth(root.left),self.maxDepth(root.right))
8+
9+
# ITERATIVE DFS
10+
classSolution:
11+
defmaxDepth(self,root:TreeNode)->int:
12+
stack= [[root,1]]
13+
res=0
14+
15+
whilestack:
16+
node,depth=stack.pop()
17+
18+
ifnode:
19+
res=max(res,depth)
20+
stack.append([node.left,depth+1])
21+
stack.append([node.right,depth+1])
22+
returnres
23+
24+
# BFS
25+
classSolution:
26+
defmaxDepth(self,root:TreeNode)->int:
27+
ifnotroot:
28+
return0
29+
30+
level=0
31+
q=deque([root])
32+
whileq:
33+
34+
foriinrange(len(q)):
35+
node=q.popleft()
36+
ifnode.left:
37+
q.append(node.left)
38+
ifnode.right:
39+
q.append(node.right)
40+
level+=1
41+
returnlevel

‎1046-Last-Stone-Weight.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
classSolution:
2+
deflastStoneWeight(self,stones:List[int])->int:
3+
stones= [-sforsinstones]
4+
heapq.heapify(stones)
5+
6+
whilelen(stones)>1:
7+
first=heapq.heappop(stones)
8+
second=heapq.heappop(stones)
9+
ifsecond>first:
10+
heapq.heappush(stones,first-second)
11+
12+
stones.append(0)
13+
returnabs(stones[0])
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
classSolution:
2+
defbuildTree(self,preorder:List[int],inorder:List[int])->Optional[TreeNode]:
3+
ifnotpreorderornotinorder:
4+
returnNone
5+
6+
root=TreeNode(preorder[0])
7+
mid=inorder.index(preorder[0])
8+
root.left=self.buildTree(preorder[1:mid+1],inorder[:mid])
9+
root.right=self.buildTree(preorder[mid+1:],inorder[mid+1:])
10+
returnroot

‎11-Container-With-Most-Water.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
classSolution:
2+
defmaxArea(self,height:List[int])->int:
3+
l,r=0,len(height)-1
4+
res=0
5+
6+
whilel<r:
7+
res=max(res,min(height[l],height[r])* (r-l))
8+
ifheight[l]<height[r]:
9+
l+=1
10+
elifheight[r]<=height[l]:
11+
r-=1
12+
returnres

‎110-Balanced-Binary-Tree.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
classSolution:
8+
defisBalanced(self,root:Optional[TreeNode])->bool:
9+
10+
defdfs(root):
11+
ifnotroot:return [True,0]
12+
13+
left,right=dfs(root.left),dfs(root.right)
14+
balanced= (left[0]andright[0]and
15+
abs(left[1]-right[1])<=1)
16+
return [balanced,1+max(left[1],right[1])]
17+
returndfs(root)[0]

‎1143-Longest-Common-Subsequence.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
classSolution:
2+
deflongestCommonSubsequence(self,text1:str,text2:str)->int:
3+
dp= [[0forjinrange(len(text2)+1)]foriinrange(len(text1)+1)]
4+
5+
foriinrange(len(text1)-1,-1,-1):
6+
forjinrange(len(text2)-1,-1,-1):
7+
iftext1[i]==text2[j]:
8+
dp[i][j]=1+dp[i+1][j+1]
9+
else:
10+
dp[i][j]=max(dp[i][j+1],dp[i+1][j])
11+
12+
returndp[0][0]

‎115-Distinct-Subsequences.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
classSolution:
2+
defnumDistinct(self,s:str,t:str)->int:
3+
cache= {}
4+
5+
foriinrange(len(s)+1):
6+
cache[(i,len(t))]=1
7+
forjinrange(len(t)):
8+
cache[(len(s),j)]=0
9+
10+
foriinrange(len(s)-1,-1,-1):
11+
forjinrange(len(t)-1,-1,-1):
12+
ifs[i]==t[j]:
13+
cache[(i,j)]=cache[(i+1,j+1)]+cache[(i+1,j)]
14+
else:
15+
cache[(i,j)]=cache[(i+1,j)]
16+
returncache[(0,0)]

‎12-Integer-To-Roman.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
classSolution:
2+
defintToRoman(self,num:int)->str:
3+
symList= [["I",1], ["IV" ,4], ["V" ,5], ["IX" ,9],
4+
["X" ,10], ["XL" ,40], ["L" ,50], ["XC" ,90],
5+
["C" ,100], ["CD",400], ["D",500], ["CM",900],
6+
["M" ,1000]]
7+
res=""
8+
forsym,valinreversed(symList):
9+
ifnum//val:
10+
count=num//val
11+
res+= (sym*count)
12+
num=num%val
13+
returnres
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
classSolution:
2+
defmaxProfit(self,prices:List[int])->int:
3+
res=0
4+
5+
l=0
6+
forrinrange(1,len(prices)):
7+
ifprices[r]<prices[l]:
8+
l=r
9+
res=max(res,prices[r]-prices[l])
10+
returnres
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
classSolution:
2+
defmaxLength(self,arr:List[str])->int:
3+
charSet=set()
4+
5+
defoverlap(charSet,s):
6+
c=Counter(charSet)+Counter(s)
7+
returnmax(c.values())>1
8+
# prev = set()
9+
# for c in s:
10+
# if c in charSet or c in prev:
11+
# return True
12+
# prev.add(c)
13+
# return False
14+
15+
defbacktrack(i):
16+
ifi==len(arr):
17+
returnlen(charSet)
18+
res=0
19+
ifnotoverlap(charSet,arr[i]):
20+
forcinarr[i]:
21+
charSet.add(c)
22+
res=backtrack(i+1)
23+
forcinarr[i]:
24+
charSet.remove(c)
25+
returnmax(res,backtrack(i+1))# dont concatenate arr[i]
26+
27+
returnbacktrack(0)

‎124-Binary-Tree-Maximum-Path-Sum.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
classSolution:
8+
defmaxPathSum(self,root:TreeNode)->int:
9+
res= [root.val]
10+
11+
# return max path sum without split
12+
defdfs(root):
13+
ifnotroot:
14+
return0
15+
16+
leftMax=dfs(root.left)
17+
rightMax=dfs(root.right)
18+
leftMax=max(leftMax,0)
19+
rightMax=max(rightMax,0)
20+
21+
# compute max path sum WITH split
22+
res[0]=max(res[0],root.val+leftMax+rightMax)
23+
returnroot.val+max(leftMax,rightMax)
24+
25+
dfs(root)
26+
returnres[0]

‎125-Valid-Palindrome.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
classSolution:
2+
defisPalindrome(self,s:str)->bool:
3+
l,r=0,len(s)-1
4+
whilel<r:
5+
whilel<randnotself.alphanum(s[l]):
6+
l+=1
7+
whilel<randnotself.alphanum(s[r]):
8+
r-=1
9+
ifs[l].lower()!=s[r].lower():
10+
returnFalse
11+
l+=1
12+
r-=1
13+
returnTrue
14+
15+
# Could write own alpha-numeric function
16+
defalphanum(self,c):
17+
return (ord('A')<=ord(c)<=ord('Z')or
18+
ord('a')<=ord(c)<=ord('z')or
19+
ord('0')<=ord(c)<=ord('9'))

‎127-Word-Ladder.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
classSolution:
2+
defladderLength(self,beginWord:str,endWord:str,wordList:List[str])->int:
3+
ifendWordnotinwordList:
4+
return0
5+
6+
nei=collections.defaultdict(list)
7+
wordList.append(beginWord)
8+
forwordinwordList:
9+
forjinrange(len(word)):
10+
pattern=word[:j]+"*"+word[j+1:]
11+
nei[pattern].append(word)
12+
13+
visit=set([beginWord])
14+
q=deque([beginWord])
15+
res=1
16+
whileq:
17+
foriinrange(len(q)):
18+
word=q.popleft()
19+
ifword==endWord:
20+
returnres
21+
forjinrange(len(word)):
22+
pattern=word[:j]+"*"+word[j+1:]
23+
forneiWordinnei[pattern]:
24+
ifneiWordnotinvisit:
25+
visit.add(neiWord)
26+
q.append(neiWord)
27+
res+=1
28+
return0

‎128-Longest-consecutive-sequence.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
classSolution:
2+
deflongestConsecutive(self,nums:List[int])->int:
3+
numSet=set(nums)
4+
longest=0
5+
6+
forninnums:
7+
# check if its the start of a sequence
8+
if (n-1)notinnumSet:
9+
length=1
10+
while (n+length)innumSet:
11+
length+=1
12+
longest=max(length,longest)
13+
returnlongest
14+

‎13-Roman-To-Integer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
classSolution:
2+
defromanToInt(self,s:str)->int:
3+
roman= {"I" :1,"V" :5,"X" :10,
4+
"L" :50,"C" :100,"D" :500,"M" :1000 }
5+
res=0
6+
foriinrange(len(s)):
7+
ifi+1<len(s)androman[s[i]]<roman[s[i+1]]:
8+
res-=roman[s[i]]
9+
else:
10+
res+=roman[s[i]]
11+
returnres

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp