classSolution { public: intmaxPower(string s){ constint n = s.size(); int l = 0, r = 0; int ans = 1; for (; r < s.size(); ++r) { if (s[r] == s[l]) continue; else { ans = max(ans, r - l); l = r; } } ans = max(ans, n - l); return ans; } };
1447. Simplified Fractions
枚举所有的分母和分子,并判断是否是最简形式。幸运的是,C++17已经内置提供gcd函数。
时间复杂度: O(n^2),
空间复杂度: O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: vector<string> simplifiedFractions(int n){ vector<string> ans; for (int down = 2; down <= n; ++down) { for (int up = 1; up < down; ++up) { if (gcd(up, down) == 1) { ans.push_back(to_string(up) + "/" + to_string(down)); } } } return ans; } };
classSolution { public: vector<string> buildArray(vector<int>& target, int n){ int i = 1; int index = 0; vector<string> ans; for (; i <= n && index < target.size(); ++i) { if (target[index] == i) { ans.push_back("Push"); ++index; } else { ans.push_back("Push"); ans.push_back("Pop"); } } return ans; } };
1442. Count Triplets That Can Form Two Arrays of Equal XOR
本题需要利用 异或 的一个性质。a ^ a = 0, a ^ b = b ^ a, (a ^ b) ^ c = a ^ (b ^ c). 即 自反律,交换律,结合律。
所以可以根据类似 presum 的操作在O(1)的时间里算出整个区间的异或值。
然后枚举 所有三元组,找到符合条件的。
classSolution: defmaxScore(self, s: str) -> int: defcount(s, c): ans = 0 for i in s: if i == c: ans += 1 return ans returnmax(count(s[:x], '0') + count(s[x:], '1') for x inrange(1,len(s)))
去年一共参加了6轮kickstart,成功拿到Google今年的实习邀请。可惜的是,由于疫情的原因,谷歌中国的暑期实习项目全部取消了。今年为了秋招名额,仍需继续参加kickstart。今天的round B轮次虽然在早上7点,但仍然有很多同学参加。遗憾的是,最后一题的时间复杂度过高,大的Test set TLE了。
1413. Minimum Value to Get Positive Step by Step Sum
统计presum的最负值,需要注意的是startValue必须是正数。
时间复杂度: O(N),
空间复杂度: O(N).
1 2 3 4 5 6 7 8
classSolution: defminStartValue(self, nums: List[int]) -> int: min_sum = 0 current_sum = 0 for i in nums: current_sum += i min_sum = min(current_sum, min_sum) return1 - min_sum if min_sum <= 0else1
1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
贪心,永远选用小于等于i的最大的Fibonacci数,然后递归解决剩余的数。
时间复杂度:O((log k)^2),
空间复杂度: O(log k).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: deffindMinFibonacciNumbers(self, k: int) -> int: deffindLargestFibonacciLessEqualThan(i): a = 1 b = 1 while a <= i: a, b = a + b, a return b defdp(i): x = findLargestFibonacciLessEqualThan(i) if x == i: return1 else: return1 + dp(i - x) return dp(k)