Minimum Moves to Equal Array Elements II

Question

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array's length is at most 10,000.

Tag

  • Maths

Thought

The target number is the mid number of the input array.

Code

class Solution(object):
    def minMoves2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums == []:
            return 0
        sort_nums = sorted(nums)
        mid = len(nums) / 2
        target_num = sort_nums[mid]
        result = 0
        for num in sort_nums:
            result += abs(num - target_num)
        return result

results matching ""

    No results matching ""