462. Minimum Moves to Equal Array Elements II

Approach 1: Reach Median

class Solution(object):
    def minMoves2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        median = nums[len(nums) / 2]
        res = 0
        for n in nums:
            res += abs(n-median)
        return res

The middle most value is the median and is at the shortest distance to reach to. Thus we can simply sort the array, find the median and evaluate the number of moves required

Time Complexity: O(NlogN)[due to sorting]

Space Complexity: O(1)

Last updated