[Leetcode学习-java]Minimum Cost to Move Chips to The Same Position(移动筹码到同一位置最小花费)

问题:

难度:easy

说明:

输入一个 int[] 代表每一个筹码(硬币一样的东西)放的位置,然后 位置 K 移动到位置 J 的时候,如果 J = K + 1 + 1 + 1 + ..... 任意个 1 或者 J = K - 1 - 1 - 1.... 相等的话,那么移动花费为 1,如果是 J = K + 2 + 2 + 2 + ..... 任意个 2 或者 J = K - 2 -  2 - 2.... 相等的话(优先判断),那么就花费为 0,这就是条阅读理解题。

相关算法题:

[Leetcode学习-java]Permutation in String(找到是否存在异序词):

https://blog.csdn.net/qq_28033719/article/details/106207925

题目连接:https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/


我的代码:

阅读理解题,其实就是判断奇偶性,看看究竟是奇数位置的筹码多还是偶数位置筹码多,选择多的一方当做移动位置,那么移动费用就是另一方的数量。写那么复杂,程序题变成语文真的好吗

class Solution {
    public int minCostToMoveChips(int[] position) {
        int odd = 0, even = 0;
        for(int i = position.length;i -- > 0;) { // hehe
            int a = (position[i] & 1) != 0 ? odd ++ : even ++;
        }
        return Math.min(even, odd);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/109526139