Weekly Contest 315
Weekly Contest 315
Problem A
Largest Positive Integer That Exists With Its Negative
思路
按照题目要求暴力求一下
代码
class Solution:
def findMaxK(self, nums: List[int]) -> int:
ans = -1
for item in nums:
if (-item) in nums:
ans = max(ans,abs(item))
return ans
Problem B
Count Number of Distinct Integers After Reverse Operations
思路
题目的本意就是将数组中每一个元素反转然后加入到数组中,求一下数组中不重复的个数,用set就行
代码
class Solution:
def countDistinctIntegers(self, nums: List[int]) -> int:
s = set()
for item in nums:
r = int(str(item)[::-1])
s.add(r)
s.add(item)
return len(s)
Problem C
Sum of Number and Its Reverse
思路
暴力遍历从小到大, 复杂度为$O(n^2)$ 不知道为啥能过
代码
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
if num == 0:
return True
for i in range(1,num):
if i == int(str(num-i)[::-1]):
return True
return False
Problem D
Count Subarrays With Fixed Bounds
思路
优先使用不在区间内的值将原数组划分成几部分,随后在每个部分中,先确定一个包含最大最小值的最小区间,然后按照一个方向延伸即可,具体实现用的双指针
代码
class Solution {
public:
long long countSubarrays(vector<int>& nums, int minK, int maxK) {
long long ret = 0;
int smin = 0, smax = 0;
for (int i = 0, j = 0, last = 0; i < nums.size(); i++) {
if (nums[i] < minK || nums[i] > maxK) {
last = j = i + 1;
smin = smax = 0;
}
else {
if (nums[i] == minK) smin++;
if (nums[i] == maxK) smax++;
while (j < i) {
if (nums[j] == minK) smin--;
if (nums[j] == maxK) smax--;
if (!smin || !smax) {
if (nums[j] == minK) smin++;
if (nums[j] == maxK) smax++;
break;
}
j++;
}
if (smin && smax) ret += j - last + 1;
}
}
return ret;
}
};
总结
出了3题,但是感觉状态越来越不好了,水平下滑有点严重。
过往不恋 未来不迎 当下不负