9.27 百度笔试 算法卷AC
先简单记一下,明天面试完在来写详细的
第一题,统计数组中,差为k的数对的个数。
思路:参考两数之和
from collections import defaultdict n,k = tuple(map(int ,input().split())) nums = list(map(int , input().split())) diffk = defaultdict(int) res = 0 for num in nums: res += diffk.get(num , 0) diffk[num + k] += 1 diffk[num - k] += 1 print(res)第二题,最少攀登的次数
思路:用一个大顶堆来维护已经爬过的山的奖励,当遇到过不去的时候,就从已经爬过的山中不断找奖励最大的来爬。
#5 3 #3 2 5 4 6 #1 2 1 3 0 #2 #1 2 #3 #100 #-1 import heapq n,k0 = tuple(map(int , input().split())) h = list(map(int , input().split())) a = list(map(int , input().split())) prev = [] heapq.heapify(prev) res = 0 k = k0 flag = 1 for i in range(n): if k >= h[i]: heapq.heappush(prev,-a[i]) else: while k < h[i] and prev != []: k -= heapq.heappop(prev) res += 1 heapq.heappush(prev,-a[i]) if k < h[i]: flag = 0 break if flag == 0: print(-1) else: print(res)