You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Deque/README.markdown
+14-11Lines changed: 14 additions & 11 deletions
Original file line number
Diff line number
Diff line change
@@ -254,11 +254,11 @@ If `head` equals 0, there is no room left at the front. When that happens, we ad
254
254
255
255
We have to do something similar for `dequeue()`. If you mostly enqueue a lot of elements at the back and mostly dequeue from the front, then you may end up with an array that looks like this:
Those empty spots at the front only get used when you use`enqueueFront()`. But if enqueuing objects at the front happens only rarely, this leaves a lot of wasted space. So let's add some code to `dequeue()` to clean this up:
261
+
Those empty spots at the front only get used when you call`enqueueFront()`. But if enqueuing objects at the front happens only rarely, this leaves a lot of wasted space. So let's add some code to `dequeue()` to clean this up:
262
262
263
263
```swift
264
264
publicmutatingfuncdequeue() -> T? {
@@ -268,26 +268,29 @@ Those empty spots at the front only get used when you use `enqueueFront()`. But
268
268
head +=1
269
269
270
270
if capacity >10&& head >= capacity*2 {
271
-
array.removeFirst(capacity)
272
-
head -= capacity
271
+
let amountToRemove = capacity + capacity/2
272
+
array.removeFirst(amountToRemove)
273
+
head -= amountToRemove
274
+
capacity /=2
273
275
}
274
276
return element
275
277
}
276
278
```
277
279
278
-
Recall that `capacity` is the original number of empty places at the front of the queue. If the `head` has advanced more to the right than twice the capacity, then it's time to trim off half of these empty spots.
280
+
Recall that `capacity` is the original number of empty places at the front of the queue. If the `head` has advanced more to the right than twice the capacity, then it's time to trim off a bunch of these empty spots. We reduce it to about 25%.
0 commit comments