You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何查找数组中元素差值为1的各唯一集合分组

Python实现相邻差1整数集合拆分最简方案

核心思路

要实现整数数组按「元素差值为1」拆分唯一集合,核心逻辑分两步:

  • 先对数组去重、升序排序,消除重复值干扰,保证遍历顺序从小到大
  • 单次遍历排序后的序列,当前元素和当前组最大值差为1就归入同一组,差值大于1就拆分新组

最简实现代码

def split_consecutive_sets(nums):
    sorted_unique = sorted(set(nums))
    if not sorted_unique:
        return []
    res = []
    cur = {sorted_unique[0]}
    for n in sorted_unique[1:]:
        if n - max(cur) == 1:
            cur.add(n)
        else:
            res.append(cur)
            cur = {n}
    res.append(cur)
    return res

# 示例测试
if __name__ == "__main__":
    test_input = [3,4,5,8,9,11]
    print(split_consecutive_sets(test_input))
    # 运行输出:[{3, 4, 5}, {8, 9}, {11}]

实现说明

  • set(nums)一步完成元素去重,匹配输出唯一集合的要求
  • 整体时间复杂度为O(nlogn),性能瓶颈在排序步骤,无额外第三方依赖,可读性强,适配绝大多数使用场景
  • 若要进一步压缩代码行数,可使用itertools.groupby实现,但会牺牲可读性,不推荐生产环境使用

内容的提问来源于stack exchange,提问作者yesyouken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 06:33:21