File tree Expand file tree Collapse file tree 3 files changed +95
-0
lines changed Expand file tree Collapse file tree 3 files changed +95
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ // Time O(V + E)
3+ // Space O(V + E)
4+ func canFinish( _ numCourses: Int , _ prerequisites: [ [ Int ] ] ) -> Bool {
5+ var indegree : [ Int ] = Array ( repeating: 0 , count: numCourses)
6+ var queue : [ Int ] = [ ]
7+ var graph : [ [ Int ] ] = Array ( repeating: [ ] , count: numCourses)
8+
9+ for i in 0 ..< prerequisites. count {
10+ let degree = prerequisites [ i] . first!
11+ let graphIndex = prerequisites [ i] [ 1 ]
12+ indegree [ degree] += 1
13+ graph [ graphIndex] . append ( degree)
14+ }
15+
16+ for i in 0 ..< indegree. count {
17+ if indegree [ i] == 0 {
18+ queue. append ( i)
19+ }
20+ }
21+
22+ var count = 0
23+
24+ while !queue. isEmpty {
25+ let current = queue. removeFirst ( )
26+ count += 1
27+ for i in graph [ current] {
28+ indegree [ i] -= 1
29+ if indegree [ i] == 0 {
30+ queue. append ( i)
31+ }
32+ }
33+ }
34+
35+ return count == numCourses
36+ }
37+ }
38+
Original file line number Diff line number Diff line change 1+ public class TreeNode {
2+ public var val : Int
3+ public var left : TreeNode ?
4+ public var right : TreeNode ?
5+ public init ( ) { self . val = 0 ; self . left = nil ; self . right = nil ; }
6+ public init ( val: Int ) { self . val = val; self . left = nil ; self . right = nil ; }
7+ public init ( val: Int , * left: TreeNode? , * right: TreeNode? ) {
8+ self . val = val
9+ self . left = left
10+ self . right = right
11+ }
12+ }
13+
14+ class Solution {
15+ // Time O(n)
16+ // Space O(n)
17+ func invertTree( _ root: TreeNode ? ) -> TreeNode ? {
18+ guard let root = root else {
19+ return nil
20+ }
21+
22+ var queue : [ TreeNode ] = [ root]
23+
24+ while queue. isEmpty == false {
25+ let current = queue. removeFirst ( )
26+
27+ if let left = current. left {
28+ queue. append ( left)
29+ }
30+
31+ if let right = current. right {
32+ queue. append ( right)
33+ }
34+
35+ ( current. left, current. right) = ( current. right, current. left)
36+ }
37+
38+ return root
39+ }
40+ }
41+
Original file line number Diff line number Diff line change 1+ class Solution {
2+ // Time O(n)
3+ // Space O(1)
4+ func canJump( _ nums: [ Int ] ) -> Bool {
5+ var maxReachIndex = 0
6+ for i in 0 ..< nums. count {
7+ if i > maxReachIndex {
8+ return false
9+ }
10+ maxReachIndex = max ( maxReachIndex, nums [ i] + i)
11+ }
12+
13+ return maxReachIndex >= nums. count - 1
14+ }
15+ }
16+
You can’t perform that action at this time.
0 commit comments