Re: [闲聊] 每日LeetCode

楼主: fxfxxxfxx (爱丽丝)   2022-10-03 09:12:35
今天的每日一题:
1578. Minimum Time to Make Rope Colorful
爱丽丝有一排有颜色的气球,要移除一些气球让相邻的气球都不同色
每个气球会有相应所需的移除时间,回传所需要的最短时间
输入:
colors: 代表气球的颜色,例如 "rrggbbb"
neededTime: 代表该气球所需的移除时间,例如 [1,2,3,4,5,6,7]
在这个例子会需要移除成 ".r.g..b",总共要花 1 + 3 + 5 + 6 = 15
想法就是,把相邻同色的都分成一群: rr | ggg | bb
每群只能留下一个,其他都要移除,所以会选择留下所需时间最大的
我的作法是遇到相邻的两个同色气球,就把小的那个拔掉
继续和下一个比,如果又同色,就会再把其中比较小的拔掉
最后就会剩下最大的
会用变量 pre 去纪录上一个气球的 index
(因为有被拔的话上一个气球就不是单纯index-1)
如果上一颗和目前的气球颜色一样的话就拔掉花费小的
class Solution {
public:
int minCost(string colors, vector<int>& neededTime) {
int n = colors.length();
int ans = 0;
int pre = 0;
for (int now = 1; now < n; now++) {
if (colors[now] != colors[pre]) {
pre = now;
} else if (neededTime[now] > neededTime[pre]) {
ans += neededTime[pre];
pre = now;
} else { // neededTime[now] <= neededTime[pre]
ans += neededTime[now];
// pre = pre
}
}
return ans;
}
};
作者: SiranuiFlare (阿火)   2022-10-03 09:13:00
大师
作者: Jaka (Jaka)   2022-10-03 09:20:00
大师
作者: Ericz7000 (Ericz7000nolan)   2022-10-03 09:21:00
大师
作者: JerryChungYC (JerryChung)   2022-10-03 09:21:00
大师
作者: sustainer123 (caster)   2022-10-03 09:23:00
大师
作者: scmono (摸诺)   2022-10-03 09:44:00
大师
作者: Rushia (みけねこ的鼻屎)   2022-10-03 11:34:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com