Last active
May 24, 2020 20:10
-
-
Save wovalle/a86a76bc20d8c886342040f54875f291 to your computer and use it in GitHub Desktop.
LeetCode May 2020
This file contains 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
// LeetCode May 2020 |
Author
wovalle
commented
May 23, 2020
// 23.js
/**
* @param {number[][]} A
* @param {number[][]} B
* @return {number[][]}
*/
var intervalIntersection = function(A, B) {
const getIntersection = (a, b) => {
if (a[1] < b[0] || a[0] > b[1])
return null
return [Math.max(a[0], b[0]), Math.min(a[1], b[1])]
}
let pivotA = 0
let pivotB = 0
const answer = []
while (pivotA < A.length && pivotB < B.length) {
const intersection = getIntersection(A[pivotA], B[pivotB])
if(intersection) {
answer.push(intersection)
}
if(A[pivotA][1] < B[pivotB][1]) {
pivotA++
} else {
pivotB++
}
}
return answer
};
// Time: O(A + B) = O(n)
// Space: O(N)
// 24.js
const getLast = (arr, level = 1) => (arr.length ? arr[arr.length - level] : null);
const bstFromPreorder = function (preorder) {
if (!preorder.length) {
return null;
}
const leaves = [[new TreeNode(preorder.shift()), -Infinity, Infinity]];
while (preorder.length) {
const currentVal = preorder.shift();
while (currentVal > getLast(leaves)[2] || currentVal < getLast(leaves)[1]) {
leaves.pop();
}
const [leave, min, max] = getLast(leaves);
if (currentVal > leave.val) {
leave.right = new TreeNode(currentVal);
leaves.push([leave.right, leave.val, max]);
} else if (currentVal < leave.val) {
leave.left = new TreeNode(currentVal);
leaves.push([leave.left, min, leave.val]);
}
}
return leaves[0][0];
};
// Time: O(n)
// Space: O(n)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment