Code Signal_练习题_absoluteValuesSumMinimization

时间:2021-08-15 08:02:23

Given a sorted array of integers a, find an integer x from a such that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)

is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

我的解答:

def absoluteValuesSumMinimization(a):
return a[len(a)//2] if len(a) % 2 == 1 else a[len(a)//2-1]
def absoluteValuesSumMinimization(A):
return A[(len(A)-1)//2]

膜拜大佬