def minMoves2(self, nums): median = sorted(nums)[len(nums) / 2] return sum(abs(num - median) for num in nums) def minMoves2(self, nums): nums.sort() return sum(nums[~i] - nums[i] for i in range(len(nums) / 2))
~ operator is the same as in C++, so
0, 1, 2, ... get turned into
-1, -2, -3, .... But C++ doesn't support negative indexing. In Python, index
-1 means the last element, index
-2 means the next-to-last element, etc.
@StefanPochmann thx. Excellent.
I think this problem should definitely be solved using numpy and vectorization. I don't understand why leetcode does not allow numpy.
leetcode does not allow numpy
Huh? What do you mean? LeetCode does offer NumPy, doesn't it?
2 lines Python, 2 ways
I have the following code that runs well on my laptop but in leetcode it says "Line 52: Exception: Type <type 'numpy.float64'>: Not implemented“
import numpy as np
def minMoves2(self, nums):
:type nums: List[int]
a = np.array(nums)
m = np.median(a)
a = a - m
a = abs(a)
@seekerwu70 Please format your code properly.
Anyway, your mistake is that your return type is wrong. The specification says you must return an
int. So just convert it. This gets accepted:
import numpy as np class Solution(object): def minMoves2(self, nums): return int(sum(abs(nums - np.median(nums))))
@StefanPochmann thanks! By the way, why is it running so slow? I assumed vectorization is usually a magnitude faster than other methods.
@seekerwu70 I tested a little, looks like importing the numpy module is responsible for the large time. (I tested by uselessly adding the import to my non-numpy solution, which made it a lot slower.)
@StefanPochmann Thanks for your elegant solution. I just want to know what made you think about median? Initially I was thinking exactly same way and only difference was I was taking round(mean) which was obviously failing some test cases.
@harshaneel Minimizing the total/average distance is just a prominent property of a median. For multi-dimensional cases you can even see it as the definition: https://en.wikipedia.org/wiki/Median#Spatial_median
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.