鱼C论坛

 找回密码
 立即注册
楼主: zltzlt

[已解决]Python:每日一题 347

[复制链接]
发表于 2020-3-10 13:41:18 | 显示全部楼层
zltzlt 发表于 2020-3-10 13:11
输入以下数据超时:
  1. def f347b(a,b):
  2.     def serch(i,b):
  3.         star = 0
  4.         end = len(b) - 1
  5.         index = (end - star) // 2
  6.         while(index != star):
  7.             if i == b[index]:
  8.                 return 0
  9.             elif i > b[index]:
  10.                 star = index
  11.             else:
  12.                 end = index
  13.             index = star + (end - star) // 2
  14.         return min(abs(i-b[star]), abs(i-b[end]))
  15.    
  16.     if len(a) == len(b) == 1:
  17.         return(abs(a[0] - b[0]))
  18.     b.sort()
  19.     result = abs(a[0]-b[0])
  20.     for i in a:
  21.         if i >= b[-1]:
  22.             dif = abs(i - b[-1])
  23.         elif i <= b[0]:
  24.             dif = abs(i - b[0])
  25.         else:
  26.             dif = serch(i,b)
  27.         if dif == 0:
  28.             return 0
  29.         elif result > dif:
  30.             result = dif
  31.     return result
复制代码

搞错了循环条件
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-10 14:16:14 | 显示全部楼层
  1. class Solution:
  2.     def smallestDifference(self, a: List[int], b: List[int]) -> int:
  3.         a.sort()
  4.         b.sort()
  5.         smallest=float('inf')
  6.         j=0
  7.         for i in range(len(a)):
  8.             last=float('-inf')
  9.             A=a[i]
  10.             for j in range(j,len(b)):
  11.                 if A<(B:=b[j]):
  12.                     smallest=min(smallest,A-last,B-A)
  13.                     break
  14.                 else:
  15.                     last=B
  16.             else:
  17.                 smallest=min(smallest,A-B)
  18.         return smallest
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-10 23:56:41 | 显示全部楼层
zltzlt 发表于 2020-3-10 13:15
你是没有理解题目意思吧

版主您老人家看看
a =[1,3,15,11,2]
b =[23,127,235,19,8]
list1 =[]
dict1 ={}
for op in a:
    for cp in b:
        if op > cp:
            
            list1.append(op-cp)
            dict1[op-cp] = op ,cp
        else:
            list1.append(cp-op)
            dict1[cp-op] = cp ,op
list1.sort()
print (list1[0],dict1[list1[0]])
现在这个对不对题
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-1 07:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表