leetcode题解(1217) Play with Chips

    1217. Play with Chips

       There are some chips, and the i-th chip is at position chips[i].

      You can perform any of the two following types of moves any number of times (possibly zero) on any chip:

  • Move the i-th chip by 2 units to the left or to the right with a cost of 0.
  • Move the i-th chip by 1 unit to the left or to the right with a cost of 1.

      There can be two or more chips at the same position initially.

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

题目的意思:给定一个位置数组,把数组中的数值移动到同一个下标数组位置下。移动的时候有这样规则:向左或者向右移动两个单元费用为0;向左或者向右移动一个单元费用为1。问:最小的费用是多少?

这个问题表述不太清楚,首先这个数组是位置数组: 

leetcode题解(1217) Play with Chips_第1张图片

 位置数组中,每一个元素对应到下标数组中的下标,目的是让位置数组中所对应的下标数组中所有元素移动到同一位置。对下标数组来说:奇数下标移动到同一位置费用为0(元素间隔为2的倍数),偶数下标移动到同一位置费用也为0,那么最终是需要移动的同一下标,就是奇数和偶数下标的最小值。

java代码如下:

class Solution {
    public int minCostToMoveChips(int[] chips) {
        int[] temp = new int[2];
        for(int a : chips){
            temp[a%2]++;
        }
        return Math.min(temp[0], temp[1]);
    }
}

 

你可能感兴趣的:(刷题,LeetCode)