forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1472-design-browser-history.swift
89 lines (74 loc) · 1.73 KB
/
1472-design-browser-history.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Question Link: https://leetcode.com/problems/design-browser-history/
*/
// Linked List Implementation
class ListNode {
var val: String
var next: ListNode?
var prev: ListNode?
init(_ val: String) {
self.val = val
}
}
class BrowserHistory {
var current: ListNode?
init(_ homepage: String) {
current = ListNode(homepage)
}
// O(1)
func visit(_ url: String) {
let node = ListNode(url)
current?.next = node
node.prev = current
current = current?.next
}
// O(n)
func back(_ steps: Int) -> String {
var steps = steps
while current?.prev != nil && steps > 0 {
current = current?.prev
steps -= 1
}
return current!.val
}
// O(n)
func forward(_ steps: Int) -> String {
var steps = steps
while current?.next != nil && steps > 0 {
current = current?.next
steps -= 1
}
return current!.val
}
}
// Array Implementation
class BrowserHistory {
var array: [String]
var count: Int
var current: Int
init(_ homepage: String) {
array = [homepage]
count = 1
current = 0
}
// O(1)
func visit(_ url: String) {
if array.count < current + 2 {
array.append(url)
} else {
array[current + 1] = url
}
current += 1
count = current + 1
}
// O(1)
func back(_ steps: Int) -> String {
current = max(current - steps, 0)
return array[current]
}
// O(1)
func forward(_ steps: Int) -> String {
current = min(current + steps, count - 1)
return array[current]
}
}