通过排序后,依次遍历前后两值求差即可,所以实质上的核心问题是排序;
通过经典的比较排序算法复杂度在O(nlogn),而如果数据波动不大,则可通过桶排序将复杂度降到O(n);
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()