算法-排序类

排序问题

1. 找到列表中的差值最小的两个值
# 找到列表中差值最小的两个数字
demo = [1, 25, 55, 9, 20]

# 首先 降序排列
demo.sort(reverse=True)
print(demo)

# 计算得到差值
demo_list = [[(demo[i] - demo[i + 1]), demo[i], demo[i + 1]] for i in range(len(demo) - 1)]
print(demo_list)

# 根据差值排序
target = sorted(demo_list, key=lambda x: x[0])
print(target)

# 取得差值最小的两个元素
print(target[0][1::])

[55, 25, 20, 9, 1]
[[30, 55, 25], [5, 25, 20], [11, 20, 9], [8, 9, 1]]
[[5, 25, 20], [8, 9, 1], [11, 20, 9], [30, 55, 25]]
[25, 20]
上一篇:小李打怪兽


下一篇:2021-09-28(剑指 Offer 55 - II. 平衡二叉树)