【LeetCode】【Math】play with chips薯条游戏
【题目】
有一堆薯条按顺序排好,第i根薯条的位置记为chips[i]。
你可以对任意薯条多次或零次执行以下的移动操作:
- 将第i根薯条向左或向右移动2个单位,费用为0.
- 将第i根薯条向左或向右移动1个单位,费用为1
最初的位置上可以有两根或多根薯条。
求将所有薯条移动至同一位置(任意位置)所需的最低成本。
Example 1:
Input: chips = [1,2,3] Output: 1 Explanation: Second chip will be moved to positon 3 with cost 1. First chip will be moved to position 3 with cost 0. Total cost is 1.
Example 2:
Input: chips = [2,2,2,3,3] Output: 2 Explanation: Both fourth and fifth chip will be moved to position two with cost 1. Total minimum cost will be 2.
Constraints:
1 <= chips.length <= 1001 <= chips[i] <= 10^9
【思路】
这道题好多人抱怨没读懂题,我也没看懂,看了例题后更迷惑了。
但实际上,每个位置上的数字是没有用的,只需考虑:移动2的倍数的代价是0,即从偶数位移动到偶数位、从奇数位移动到奇数位的代价是0,从偶数位移到奇数位、从奇数位移动到偶数位的代价是1,我们只需尽量减少后者的移动。
题目要求最后所有的薯条要在同一位置(奇数位或偶数位)。 因此,我们要计算将所有奇数个薯条移动到偶数还是将所有偶数个薯条移动到奇数便宜。 这可以简单地归结为计算我们开始时有多少个偶数薯条,以及有多少个奇数薯条。 每个必须移动的薯条的代价均为1。
【解法】
class Solution: def minCostToMoveChips(self, chips: List[int]) -> int: even_parity = 0 odd_parity = 0 for chip in chips: if chip % 2 == 0: even_parity += 1 else: odd_parity += 1 return min(even_parity, odd_parity)
Runtime: 36 ms, faster than 40.30% of Python3 online submissions for Play with Chips.
Memory Usage: 13.9 MB, less than 41.95% of Python3 online submissions for Play with Chips.
【解法】另一种写法
class Solution: def minCostToMoveChips(self, chips: List[int]) -> int: odds = sum(x % 2 for x in chips) return min(odds, len(chips) - odds)
Runtime: 32 ms, faster than 69.65% of Python3 online submissions for Play with Chips.
Memory Usage: 13.8 MB, less than 72.41% of Python3 online submissions for Play with Chips.
【解法】写法三
def minCostToMoveChips(self, chips: List[int]) -> int: cnt = [0, 0] for chip in chips: cnt[chip % 2] += 1 return min(cnt)
Runtime: 28 ms, faster than 88.53% of Python3 online submissions for Play with Chips.
Memory Usage: 14 MB, less than 15.80% of Python3 online submissions for Play with Chips.

浙公网安备 33010602011771号