[算法] 求无序数组元素最小差值

通过排序后,依次遍历前后两值求差即可,所以实质上的核心问题是排序;

通过经典的比较排序算法复杂度在O(nlogn),而如果数据波动不大,则可通过桶排序将复杂度降到O(n);

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
array = (5, 2, 4, 9, 0, 6)
 
# quick sort
# O(nlogn)
def split(list, start, end):
    middle = list[end]
    index = start -1
    for i in range(start, end+1):
        if list[i] <= middle:
            index += 1
            temp = list[i]
            list[i] = list[index]
            list[index] = temp
 
    return index
 
def quick_sort(list, start, end):
    if (start < end):
        index = split(list, start, end)
        quick_sort(list, start, index-1)
        quick_sort(list, index+1, end)
 
# bucket sort
def bucket_sort(list):
    max_e = list[0]
    min_e = list[0]
 
    # max & min element
    for i in list:
        if i > max_e:
            max_e = i
        if i < min_e:
            min_e = i
 
    bucket_v = max_e - min_e + 1
    B = []
    for i in range(bucket_v):
        B.append(0)
    for i in list:
        B[i - min_e] += 1
    return B
 
def min_diff():
    l = list(array)
 
    # sort
    B = bucket_sort(l)
    first = True
    diff = -1
    for i in range(len(B)):
        if B[i] >= 2:
            diff = 0
            break
        elif B[i] == 1 and first:
            low = i
            first = False
        elif B[i] == 1: # ! first
            high = i
            tmp_diff = high - low
            if (diff < 0 or tmp_diff < diff):
                diff = tmp_diff
            low = i
        # else B[i] == 0, ignore
 
    print "min diff from bucket sort:", diff
 
    # qsort
    quick_sort(l, 0, len(l)-1)
    first = True
    diff = -1
    for i in l:
        if first:
            low = i
            first = False
        else:
            high = i
            tmp_diff = high - low
            if (diff < 0 or tmp_diff < diff):
                diff = tmp_diff
            low = i
 
    print "min diff from quick sort:", diff
 
if __name__ == "__main__":
    print array
    min_diff()

 

posted @   ZisZ  阅读(1666)  评论(0编辑  收藏  举报
编辑推荐:
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)
点击右上角即可分享
微信分享提示