File tree Expand file tree Collapse file tree 3 files changed +108
-0
lines changed Expand file tree Collapse file tree 3 files changed +108
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ // Time O(n log n)
3+ // Space O(n)
4+ func merge( _ intervals: [ [ Int ] ] ) -> [ [ Int ] ] {
5+ if intervals. count <= 1 {
6+ return intervals
7+ }
8+
9+ let intervals = intervals. sorted { $0 [ 0 ] <= $1 [ 0 ] }
10+ var answer : [ [ Int ] ] = [ ]
11+ var currentInterval : [ Int ] = [ ]
12+
13+ for i in 0 ..< intervals. count {
14+ if currentInterval. isEmpty {
15+ currentInterval = intervals [ i]
16+ }
17+
18+ if intervals [ i] [ 0 ] >= currentInterval [ 0 ] && intervals [ i] [ 0 ] <= currentInterval [ 1 ] {
19+ currentInterval = [ currentInterval [ 0 ] , max ( currentInterval [ 1 ] , intervals [ i] [ 1 ] ) ]
20+ } else {
21+ answer. append ( currentInterval)
22+ currentInterval = intervals [ i]
23+ }
24+ }
25+
26+ answer. append ( currentInterval)
27+
28+ return answer
29+ }
30+ }
31+
Original file line number Diff line number Diff line change 1+ class Solution {
2+ // Time O(n)
3+ // Space O(1)
4+ func missingNumber( _ nums: [ Int ] ) -> Int {
5+ var sum = 0
6+ for i in 0 ..< nums. count {
7+ sum += i
8+ sum -= nums [ i]
9+ }
10+
11+ return sum + nums. count
12+ }
13+ }
14+
Original file line number Diff line number Diff line change 1+ public class ListNode {
2+ public var val : Int
3+ public var next : ListNode ?
4+ public init ( ) { self . val = 0 ; self . next = nil ; }
5+ public init ( _ val: Int ) { self . val = val; self . next = nil ; }
6+ public init ( _ val: Int , _ next: ListNode ? ) { self . val = val; self . next = next; }
7+ }
8+
9+ class Solution {
10+ // Time O(n)
11+ // Space O(1)
12+ func reorderList( _ head: ListNode ? ) {
13+ guard let head = head, head. next != nil , head. next? . next != nil else {
14+ return
15+ }
16+
17+ var slow = head
18+ var fast = head
19+
20+ while fast. next != nil && fast. next? . next != nil {
21+ slow = slow. next!
22+ fast = fast. next!. next!
23+ }
24+
25+ let secondHalf = slow. next
26+ slow. next = nil
27+
28+ let reversedSecondHalf = reverseList ( secondHalf)
29+
30+ mergeLists ( head, reversedSecondHalf)
31+ }
32+
33+ private func reverseList( _ head: ListNode ? ) -> ListNode ? {
34+ var prev : ListNode ? = nil
35+ var current = head
36+
37+ while current != nil {
38+ let nextTemp = current? . next
39+ current? . next = prev
40+ prev = current
41+ current = nextTemp
42+ }
43+
44+ return prev
45+ }
46+
47+ private func mergeLists( _ list1: ListNode ? , _ list2: ListNode ? ) {
48+ var first = list1
49+ var second = list2
50+
51+ while first != nil && second != nil {
52+ let firstNext = first? . next
53+ let secondNext = second? . next
54+
55+ first? . next = second
56+ second? . next = firstNext
57+
58+ first = firstNext
59+ second = secondNext
60+ }
61+ }
62+ }
63+
You can’t perform that action at this time.
0 commit comments