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.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

Source: leetcode | Difficulty: MEDIUM_HARD
Tags: Sorting

Data structures

Mathematics

Starter code: class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        

Solutions:
class Solution:

	def minMoves2(self, nums):
		aa = sorted(nums)
		median = aa[len(nums) // 2]
		return sum([abs(i - median) for i in aa])


class Solution:

	def minMoves2(self, nums):
		nums.sort()
		median = nums[len(nums) // 2]
		return sum([abs(i - median) for i in nums])


class Solution:

	def minMoves2(self, nums):
		mid = len(nums) // 2
		tar = sorted(nums)[mid]
		return sum([abs(x - tar) for x in nums])


class Solution:

	def minMoves2(self, nums):
		snums = sorted(nums)
		count = 0
		for i in snums:
			count += abs(i - snums[int(len(nums) / 2)])
		return count


class Solution:

	def minMoves2(self, nums):
		median = sorted(nums)[len(nums) // 2]
		return sum((abs(num - median) for num in nums))


class Solution:

	def minMoves2(self, nums):
		med = 0
		nums.sort()
		final = 0
		final1 = 0
		if len(nums) % 2 != 0:
			med = int(len(nums) / 2)
			for j in range(med):
				final = final + abs(nums[med] - nums[j])
			for g in range(med, len(nums)):
				final = final + abs(nums[med] - nums[g])
		else:
			med = int(len(nums) / 2)
			for k in range(med):
				final = final + abs(nums[med] - nums[k])
			for t in range(med, len(nums)):
				final = final + abs(nums[med] - nums[t])
			med = int(len(nums) / 2) - 1
			for h in range(med):
				final1 = final1 + abs(nums[med] - nums[h])
			for q in range(med, len(nums)):
				final1 = final1 + abs(nums[med] - nums[q])
			final = min(final, final1)
		return final


class Solution:

	def minMoves2(self, nums):
		nums = sorted(nums)
		mid_x = nums[len(nums) // 2]
		count = 0
		for x in nums:
			count += abs(x - mid_x)
		return count


class Solution:

	def minMoves2(self, nums):
		length = len(nums)
		nums = sorted(nums)
		median = nums[length // 2]
		steps = [abs(x - median) for x in nums]
		return sum(steps)