Weekly Contest 316

Weekly Contest 316

Problem A

Determine if Two Events Have Conflict

思路

先将时间转化为分钟单位,然后根据大小判断有没有交集即可

代码

class Solution:
    def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
        tp1 = [int(event1[0][:2])*60+int(event1[0][3:]),int(event1[1][:2])*60+int(event1[1][3:])]
        tp2 = [int(event2[0][:2])*60+int(event2[0][3:]),int(event2[1][:2])*60+int(event2[1][3:])]
        if tp1<=tp2:
            if tp1[1]>=tp2[0]:
                return True
            else:
                return False
        else:
            if tp1[0]<=tp2[1]:
                return True
            return False

Problem B

Number of Subarrays With GCD Equal to K

思路

这题数据范围比较小,枚举起点然后算就行了

代码

import math
class Solution:
    def subarrayGCD(self, nums: List[int], k: int) -> int:
        n = len(nums)
        cnt = 0
        for i in range(n):
            if nums[i]==k:
                cnt+=1
            t = nums[i]
            for j in range(i+1,n):
                t = gcd(t,nums[j])
                if t == k:
                    # print(nums[])
                    cnt+=1
        return cnt

Problem C

Minimum Cost to Make Array Equal

思路

枚举最后的均值,在计算代价时使用了increase和decrease两个数组,increase数组表示讲当前位置之前的数同化到当前的数的所需要cost,decrease则表示将之后的值同化所需要的cost,所以当前的代价就是increase[i]+decrease[i],取最小值就行

代码

class Solution:
    def minCost(self, nums: List[int], cost: List[int]) -> int:
        n = len(nums)
        ids = sorted(range(n), key=lambda x: nums[x])
        nums = [nums[i] for i in ids]
        cost = [cost[i] for i in ids]
        scost = list(accumulate(cost))
        
        increase = [0 for _ in range(n)]
        for i in range(1, n):
            increase[i] = increase[i-1] + scost[i-1] * (nums[i] - nums[i-1])
        
        decrease = [0 for _ in range(n)]
        for i in range(n-2, -1, -1):
            decrease[i] = decrease[i+1] + (scost[-1] - scost[i]) * (nums[i+1] - nums[i])
            
        return min(increase[i] + decrease[i] for i in range(n))

Problem D

Minimum Number of Operations to Make Arrays Similar

思路

题目保证一定有解,并且每次操作都是$\pm 2$所以可以认为偶找偶,奇找奇。最后计算下结果就行了。

代码

class Solution:
    def makeSimilar(self, nums: List[int], target: List[int]) -> int:
        odds1 = sorted([x for x in nums if x % 2 == 1])
        evens1 = sorted([x for x in nums if x % 2 == 0])
        
        odds2 = sorted([x for x in target if x % 2 == 1])
        evens2 = sorted([x for x in target if x % 2 == 0])
        
        def cnt(src, tgt):
            return sum(max(0, x-y) for x, y in zip(src, tgt)) // 2
        
        return cnt(odds1, odds2) + cnt(evens1, evens2)
 

总结

出了两题,后面两个构造题感觉没啥思路,所以没做出来。

posted @ 2022-11-12 16:10  浅花迷人  阅读(8)  评论(0编辑  收藏  举报