5 ms·
push: a = append(a, el) pop: n := len(a) el := a[n-1] a = a[:n-1] It took me, literally, 10 seconds to write.
by kjksf 8y ago
push:
a = append(a, el)
pop:
n := len(a)
el := a[n-1]
a = a[:n-1]
It took me, literally, 10 seconds to write.
- newen 8y agoIs that an O(n) implementation of pop? I hope you realize my point.. I looked it up and it's not but the point is that you shouldn't have to worry about these things, including implementation details of trees and hundreds of other data structures.
- oconnor663 8y agoIt isn't. It re-slices the backing array and retains its capacity. (Maybe that's what you looked up at the end?)
- stouset 8y agoMore importantly, this will take me a minute to read and two minutes to make sure it’s doing the right thing every time I encounter it somewhere new. I don’t think I will ever understand why so many go advocates seem so openly hostile to encapsulation. If go had used C-style for loops, I swear there would be people here defending the decision saying: sum := 0 for (i := 0; i <= len(a); i++) { sum = sum + a[1] } “See? Only four lines. What’s the big deal? It took me literally thirty seconds to write.”
- stouset 8y agoDid you immediately notice the bug in my above code? If not, hopefully you get my point. Compared to array.sum() was the above code more or less clear? Is it more or less prone to bugs? When reading, which code will you have a quicker understanding of the intent? And if you did notice the the first bug, did you notice the second bug?
- kortex 8y agoWell played. I noticed neither until you pointed them out. Certainly would have missed it in a code review.
- h8hawk 8y agoThis code is inefficient.
- tedunangst 8y agoTune in next week to find out why!
- oconnor663 8y agoI think parent should've made their point with a queue instead of a stack.