Leetcode Weekly Contest 297
今天嘗試解了 Hard,有一題 Medium 是圖形相關,題目太長直接懶得看,另一題分餅乾的需要 Greedy Algorithm,直接超出知識範圍。最後想說來試試看 Hard。
2303. Calculate Amount Paid in Taxes
Difficulty: Easy
, Open in Leetcode
You are given a 0-indexed 2D integer array brackets
where brackets[i] = [upperi, percenti]
means that the ith
tax bracket has an upper bound of upperi
and is taxed at a rate of percenti
. The brackets are sorted by upper bound (i.e. upperi-1 < upperi
for 0 < i < brackets.length
).
Tax is calculated as follows:
- The first
upper0
dollars earned are taxed at a rate ofpercent0
. - The next
upper1 - upper0
dollars earned are taxed at a rate ofpercent1
. - The next
upper2 - upper1
dollars earned are taxed at a rate ofpercent2
.
And so on.
You are given an integer income
representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10^5
of the actual answer will be accepted.
題目解釋
計算你的收入 income
要被抽多少稅
以題目來說 [[3,50],[7,10],[12,25]]
,前面 3 塊要 50%,接下來的 4 塊要 10%,接下來的 5 塊要 25%
Solution
就很暴力,先把 brackets 從後面跑過一遍算出每個級距的錢,接著再跑過一遍算錢。
1 | def calculateTax(self, brackets: List[List[int]], income: int) -> float: |
2306. Naming a Company
Difficulty: Hard
, Open in Leetcode
You are given an array of strings ideas
that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
- Choose 2 distinct names from
ideas
, call themideaA
andideaB
. - Swap the first letters of
ideaA
andideaB
with each other. - If both of the new names are not found in the original
ideas
, then the nameideaA
ideaB
(the concatenation ofideaA
andideaB
, separated by a space) is a valid company name. - Otherwise, it is not a valid name.
Return the number of distinct valid names for the company.
題目解釋
Solution
看看題目限制寫到 2 <= ideas.length <= 5 * 10^4
,吃到 TLE 完全不意外
1 | def distinctNames(self, ideas: List[str]) -> int: |
所以讓來看看大神的思路:[Python 3] Explanation with pictures
- 用第一個字母把
ideas
分組 - 挑兩個出來比的時候,如果同一個字在這兩個 set() 都有出現,那這個字一定不會是 valid name
- 把這些字從各自的 list 中扣掉,算出 list 中獨特的字有幾個
- 把兩個 list 中獨特的數乘起來,就是一半的 valid name,另一半可以再 x2 ,也就是由
A B
變成B A
的意思。
1 | def distinctNames(self, ideas: List[str]) -> int: |