ChatGPT vs. Logic:为什么 AI 代码更慢

发布: (2026年2月7日 GMT+8 03:13)
2 min read
原文: Dev.to

Source: Dev.to

第 1 轮:ChatGPT 方法

lst = [44,4,4,1,1,1,1,1,1,1,12,4,3,2,4,5,6,4,3,44,556,6,6,6,6,22,2,2,1]

# Step 1: Find lowest value manually
lowest = lst[0]
for num in lst:
    if num < lowest:
        lowest = num

# Step 2: Find all indexes of lowest value
result = {}
indexes = []
for i in range(len(lst)):
    if lst[i] == lowest:
        indexes.append(i)
result[lowest] = indexes
print(result)

优化的单遍历方法

lst = [44, 4, 4, 1, 1, 1, 1, 1, 1, 1, 12, 4, 3, 2, 4, 5, 6, 4, 3, 44, 556, 6, 6, 6, 6, 22, 2, 2, 1]

final_dict = {}
temp = float("inf")
for i, v in enumerate(lst):
    if v < temp:
        temp = v
        final_dict.clear()
        final_dict[v] = [i]
    elif v == temp:
        final_dict[v].append(i)

print(final_dict)

复杂度与短路效应

  • O(N) 复杂度 – 列表仅遍历一次。
  • 短路效应 – 在找到最小值(例如 1)后,后续更大的数字将不再用于字典更新。

2026 年开发者结论

在 AI 时代,轻易满足于“能跑通的代码”变得很常见。高性能工程会问:两次循环的解法能否压缩为一次遍历?

讨论: 你是更看重逐步可读性,还是始终追求单遍历的优化?

标签: python performance algorithms codingchallenge

Back to Blog

相关文章

阅读更多 »

问题 12:寻找目标和的配对

问题描述:编写一个函数,找出列表中所有唯一的数字对,使其和等于给定的目标和(target sum)。函数应返回一个列表…