Algorithms and Data Structures brush title

1. Find the minimum rotation of the array

Description rotating array, such as [-2, 3, 5, 6, 9, -10, -5], is characterized by the sequence of the left array to make a good part moves to the right.
[Thinking] binary search

def find_min(li):
    l = 0
    r = len(li)
    m = int(r/2)

    if li[l] < li[m]:
        # 此时是左边递增,最小值位于右边
        return find_min(li[m+1:r])
    elif li[l] > li[m]:
        # 最小值位于mid左面,包含mid
        return find_min(li[l:m+1])
    else:
        return li[mid]

2. Zero and arrays

Description element and the sub-array closest to 0
[idea] referred to 1-n and the elements s (n), then there are two cases, S (n) and S (m) -S (n) . The second of which can be sorted, it does take two neighboring poor. Sort complexity nlog (n).

from collections import OrderedDict
from copy import deepcopy

def get_mini_sublist(li):
    part1_index = {}
    part2_index = {}
    
    # 第一部分,前n项求和
    for i in range(1, len(li)):
        part1_index[(0, i)] = sum(li[:i])
    part1_index = OrderedDict(sorted(part1_index.items(), key=lambda x:x[1] ))
    
    # 第二部分,排序,做差
    t1 = deepcopy(part1_index).popitem(last=True), 
    t2 = deepcopy(part1_index).popitem(last=False)
    
    for i,j in zip(t1.items(), t2.items()):
        part2_index[(i[0][1], j[0][1])] = j[1]-i[1]
    
    # 融合,然后取值最小值    
    part2_index.update(part1_index)         
    key_min = min(part2_index, key=lambda x:abs(part2_index[x])
    return key_min, part2_index[key_min]

Guess you like

Origin www.cnblogs.com/geoffreyone/p/11506019.html