Created
August 2, 2016 06:02
-
-
Save jooyunghan/2be52dee6e2793b8f529b1278fa5a7ac to your computer and use it in GitHub Desktop.
LeetCode kth smallest using Generator(JS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function* gen(g) { | |
yield* g | |
} | |
function kth(k, g) { | |
while (k-- > 0) g.next() // 문제는 1부터라 0대신 1 | |
return g.next().value | |
} | |
function* merge(g1, g2) { | |
let n1 = g1.next() | |
let n2 = g2.next() | |
while (!n1.done && !n2.done) { | |
if (n1.value < n2.value) { | |
yield n1.value | |
n1 = g1.next() | |
} else { | |
yield n2.value | |
n2 = g2.next() | |
} | |
} | |
if (!n1.done) { | |
yield n1.value | |
yield* g1 | |
} | |
if (!n2.done) { | |
yield n2.value | |
yield* g2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var kthSmallest = function (matrix, k) {
return kth(k, matrix.map(gen).reduce(merge));
};