current position:Home>leetcode:462. Minimum number of moves to make array elements equal II [sort + find the middle]

leetcode:462. Minimum number of moves to make array elements equal II [sort + find the middle]

2022-04-29 20:25:13Review of the white speed Dragon King

 Insert picture description here

analysis

After sorting, find the middle as target, Ask for all target The sum of the distances
Be careful , If it's even , Two target Calculate it all, find a minimum value and seek stability

ac code

class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        #  Lean in the middle 
        n = len(nums)
        nums.sort()
        #  Special judgement 
        if n == 1:
            return 0
        
        if n % 2 == 1:
            target = nums[n // 2]
            ans = 0
            for i in range(n):
                ans += abs(nums[i] - target)
            return ans
        else:
            target1, target2 = nums[n // 2 - 1], nums[n // 2]
            ans1, ans2 = 0, 0
            for i in range(n):
                ans1 += abs(nums[i] - target1)
                ans2 += abs(nums[i] - target2)
            return min(ans1, ans2)

summary

Simple sorting and finding rules

copyright notice
author[Review of the white speed Dragon King],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291605388969.html

Random recommended