LeetCode #1217. Minimum Cost to Move Chips to The Same Position

题目

1217. Minimum Cost to Move Chips to The Same Position


解题方法

遍历数组,统计奇数和偶数的个数,返回其最小值即可。这道题其实可以这样来想,既然跳两次的cost是0,就默认所有1、3、5、...、2n+1位置的chips都处于同一个位置1,而剩余的chips都在同一个位置2,那么显然无法避免的cost就是把所有1的chips跳到2上或者把所有2的chips跳到1上,取决于哪个位置的chips更少。
时间复杂度:O(n)
空间复杂度:O(1)


代码

class Solution:
    def minCostToMoveChips(self, position: List[int]) -> int:
        length1 = length2 = 0
        for i in position:
            if not i % 2:
                length1 += 1
            else:
                length2 += 1
        
        return min(length1, length2)
posted @ 2020-11-24 15:34  老鼠司令  阅读(102)  评论(0)    收藏  举报