1899. Merge Triplets to Form Target Triplet
題目網址:https://leetcode.cn/problems/merge-triplets-to-form-target-triplet/
題意:triplet 是由三個整數所組成的 array。給一 2D 整數 array
triplets
, 其中triplets[i] = [ai, bi, ci]
表示第i
個 triplet。並給一整數 arraytarget = [x, y, z]
, 表示你想要得到的 triplet。為了得到
target
, 你需要對triplets
進行下面的操作任意次(也可能是0
次):
- 選出兩個 index(index 從
0
開始)i
和j
(i != j
), 並更新triplets[j]
為[max(ai, aj), max(bi, bj), max(ci, cj)]
e.g.
triplets[i] = [2, 5, 3]
且triplets[j] = [1, 7, 5]
➔ 則
triplets[j]
將會更新為[max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]
。若透過上述操作可使得
target
成為triplets
中的元素, 則返回true
;否則, 返回false
。
Solution:
想法:利用 Greedy, 令
x = target[0]
,y = target[1]
,z = target[2]
, 且ai = triplet[0]
,bi = triplet[1]
,ci = triplet[2]
。若ai > x
或bi > y
或ci > z
, 則跳過該 triplet, 因為若拿該 triplet 做運算(a, b, c)
一定不等於(x, y, z)
。否則, 更新a, b, c
。最後判斷(a, b, c)
是否等於(x, y, z)
class Solution { |
- time:$O(n)$ ➔ 遍歷
triplets
- space:$O(1)$ ➔ 只需常數空間
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論