mongona

mongona
-- --
正在获取天气

返回指定数组元素差的demo

# -*- coding: utf-8 -*-
"""
@author: sato
@file: test.py
@time: 2019-08-30 00:16

"""
alist = [11, 2, 4, 55, 77, 9]
t = 75  # 77 - 2


def solution(arr, target):
    """遍历两次 O(n^n)"""
    for i in range(len(arr)):
        for j in range(len(arr[i:])):
            if abs(arr[i] - arr[j]) == target:
                return [i, j]


result = solution(arr=alist, target=t)

print(result)


def solution2(arr, target):
    """构造一个map"""
    tmp_dict = dict()
    for i in range(len(arr)):
        tmp_dict[abs(target - arr[i])] = i
    for j in range(len(arr)):
        if tmp_dict.get(arr[j]):
            print([j, tmp_dict.get(arr[j])])


solution2(arr=alist, target=t)

 

2
0
富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善。
打赏二维码