-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a9814b2
commit ec65ff1
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
from collections import defaultdict | ||
|
||
|
||
class Solution: | ||
def getAncestors(self, n, edges): | ||
graph = defaultdict(list) | ||
res = {i: [] for i in range(n)} | ||
|
||
for edge in edges: | ||
graph[edge[0]].append(edge[1]) | ||
|
||
def dfs(parent, child): | ||
res[child].extend(res[parent]) | ||
if parent not in res[child]: | ||
res[child].append(parent) | ||
res[child] = sorted(set(res[child])) | ||
if child in graph: | ||
parent = child | ||
for child in graph[parent]: | ||
dfs(parent, child) | ||
else: | ||
return | ||
|
||
|
||
for edge in edges: | ||
dfs(edge[0], edge[1]) | ||
|
||
res = dict(sorted(res.items())) | ||
return list(res.values()) | ||
|
||
|
||
sln = Solution() | ||
print(sln.getAncestors( | ||
9, [[7, 5], [2, 5], [0, 7], [0, 1], [6, 1], [2, 4], [3, 5]])) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
from collections import deque | ||
|
||
|
||
class Solution: | ||
def longestSubarray(self, nums, limit): | ||
min_q = deque() | ||
max_q = deque() | ||
|
||
l = 0 | ||
res = 0 | ||
|
||
for r in range(len(nums)): | ||
while min_q and nums[r] < min_q[-1]: | ||
min_q.pop() | ||
while max_q and nums[r] > max_q[-1]: | ||
max_q.pop() | ||
|
||
min_q.append(nums[r]) | ||
max_q.append(nums[r]) | ||
|
||
while min_q and max_q and (max_q[0]-min_q[0]) > limit: | ||
if nums[l] == max_q[0]: | ||
max_q.popleft() | ||
if nums[l] == min_q[0]: | ||
min_q.popleft() | ||
l += 1 | ||
res = max(res, r-l+1) | ||
|
||
return res | ||
|
||
|
||
sln = Solution() | ||
result = sln.longestSubarray([8, 2, 4, 7], 4) | ||
print(result) |