forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1899-merge-triplets-to-form-target-triplet.js
70 lines (59 loc) · 1.86 KB
/
1899-merge-triplets-to-form-target-triplet.js
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
/**
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function (triplets, target) {
var good = new Set();
for (var t in triplets) {
var triplet = triplets[t];
if (
triplet[0] > target[0] ||
triplet[1] > target[1] ||
triplet[2] > target[2]
) {
continue;
}
for (var i = 0; i < triplet.length; i++) {
if (triplet[i] === target[i]) {
good.add(i);
}
}
}
return good.size === 3;
};
/**
* https://leetcode.com/problems/merge-triplets-to-form-target-triplet/
* Time O(N) | Space O(1)
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function(triplets, target, res = new Array(3).fill(0)) {
for (const [ a, b, c ] of triplets) { /* Time O(N) */
const [ _a, _b, _c ] = target;
const isTargetGreater = (a <= _a) && (b <= _b) && (c <= _c);
if (!isTargetGreater) continue;
const [ __a, __b, __c ] = res;
res = [ Math.max(__a, a), Math.max(__b, b), Math.max(__c, c) ];
}
return res.every((val, i) => val === target[i])/* Time O(N) */
};
/**
* https://leetcode.com/problems/merge-triplets-to-form-target-triplet/
* Time O(N) | Space O(1)
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function(triplets, target, res = new Array(3).fill(false)) {
for (const [ a, b, c ] of triplets) {/* Time O(N) */
const [ _a, _b, _c ] = target;
const isTargetGreater = (a <= _a) && (b <= _b) && (c <= _c);
if (!isTargetGreater) continue;
res[0] |= (a === _a);
res[1] |= (b === _b);
res[2] |= (c === _c);
}
return res[0] && res[1] && res[2];
}