zoukankan      html  css  js  c++  java
  • 1217. Play with Chips

    问题:

    给定一个数组,表示了每一个chip的所在位置。

    有以下的移动规则

    1.每向左or向右移动2个单位,消耗为0

    2.没向左or向右移动1个单位,消耗为1

    求将所有chip都移动到同一个位置,消耗最小是多少?

    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 <= 100
    1 <= chips[i] <= 10^9
    

      

    解法:

    问题分析:

    由移动规则可知,任一chip移动到任何位置,

    所需消耗为:0或者1.

    (比如需要移动6个单元,即移动2+2+2,3次2单位移动,每次耗费0,总消耗为0)
    (比如需要移动7个单元,即移动2+2+2+1,3次2单位+1次1单位移动,3次耗费0,1次耗费1,总消耗为1)

    即,有两种情况,

    1.将所有chip移动到一个奇数位。

    那么奇数位上的chip,相对目的位置移动2的倍数次,消耗为0,

    所有奇数位上的chip总消耗为【0】。

    偶数位上的chip,相对目的位置移动2的倍数+1次,消耗为1

    所有偶数位上的chip总消耗为【chip数*1】。

    2.将所有chip移动到一个偶数位。

    那么偶数位上的chip,相对目的位置移动2的倍数次,消耗为0,

    所有偶数位上的chip总消耗为【0】。

    奇数位上的chip,相对目的位置移动2的倍数+1次,消耗为1

    所有奇数位上的chip总消耗为【chip数*1】。

    那么问题转换为:

    求奇数位和偶数位上的chip数,最终求这两种情况的最小值即可。

    代码参考:

     1 class Solution {
     2 public:
     3     int minCostToMoveChips(vector<int>& chips) {
     4         int oddevenc[2]={0};
     5         for(int c:chips){
     6             oddevenc[c%2]++;
     7         }
     8         return min(oddevenc[0], oddevenc[1]);
     9     }
    10 };
  • 相关阅读:
    Delphi cxGrid –--> RecordIndex out of Range
    局域网共享需要密码
    提高AdoQuery的速度
    string literals may have at most 255 elements
    delphi控件属性大全-详解-简介
    Cxgrid获取选中行列,排序规则,当前正在编辑的单元格内的值
    FastReport 使用说明
    delphi的取整函数round、trunc、ceil和floor
    cxGrid 速度
    SQL Server 无法在服务器上访问指定的路径或文件解决方法
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13283083.html
Copyright © 2011-2022 走看看