leetcode 1217. Minimum Cost to Move Chips to The Same Position(python)

328 阅读1分钟

描述

We have n chips, where the position of the ith chip is position[i].

We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:

  • position[i] + 2 or position[i] - 2 with cost = 0.
  • position[i] + 1 or position[i] - 1 with cost = 1.

Return the minimum cost needed to move all the chips to the same position.

Example 1:

Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.	

Example 2:

Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at position  3 to position 2. Each move has cost = 1. The total cost = 2.

Example 3:

Input: position = [1,1000000000]
Output: 1

Note:

1 <= position.length <= 100
1 <= position[i] <= 10^9

解析

根据题意和栗子可以看出来,不管多远的距离,只要 position 中的数字相差的距离是 2 的倍数消耗都是 0 ,数字相差的距离无法对 2 取余则消耗为 1 。position 中只有两类数字,一类是偶数,一类是奇数。如果只是一类(偶数或者奇数),那么不管将所有的分片移动到某个位置上的操作消耗都始终为 0 。而如果同时有奇数和偶数,最后的消耗就是 min(偶数个数,奇数个数) 。

解答

class Solution(object):
    def minCostToMoveChips(self, position):
        """
        :type position: List[int]
        :rtype: int
        """
        odd = 0
        even = 0
        for num in position:
            if num % 2 == 0:
                even += 1
            else:
                odd += 1
        return min(even, odd)        	      
		

运行结果

Runtime: 24 ms, faster than 43.78% of Python online submissions for Minimum Cost to Move Chips to The Same Position.
Memory Usage: 13.4 MB, less than 75.62% of Python online submissions for Minimum Cost to Move Chips to The Same Position.

原题链接:leetcode.com/problems/mi…

您的支持是我最大的动力