Leetcode 1217. 玩筹码

在这里插入图片描述
有 n 个筹码。第 i 个芯片的位置是 position[i] 。

我们需要把所有筹码移到同一个位置。在一步中,我们可以将第 i 个芯片的位置从 position[i] 改变为:

  • position[i] + 2 或 position[i] - 2 ,此时 cost = 0
  • position[i] + 1 或 position[i] - 1 ,此时 cost = 1

返回将所有筹码移动到同一位置上所需要的 最小代价 。

示例 1:

在这里插入图片描述

输入:position = [1,2,3]
输出:1
解释:第一步:将位置3的芯片移动到位置1,成本为0。
第二步:将位置2的芯片移动到位置1,成本= 1。
总成本是1。

示例 2:
在这里插入图片描述

输入:position = [2,2,2,3,3]
输出:2
解释:我们可以把位置3的两个芯片移到位置2。每一步的成本为1。总成本= 2。

示例 3:

输入:position = [1,1000000000]
输出:1

提示:

  • 1 <= chips.length <= 100
  • 1 <= chips[i] <= 10^9

主要思路:这道题目如果没想好可能就会很难做出来,
想了半天,发现主要是考你统计奇数和偶数个数问题,哪个少就是答案(记得要全部累加)
Code:

class Solution {
public:
    int minCostToMoveChips(vector<int>& position) {
        int res=0;
    map<int,int>mymap;

    int num1=0;
    int num2=0;
    for(int i=0;i<position.size();i++)
    {
        mymap[position[i]]++;
        if(position[i]%2)
            num1++;
        else
            num2++;
    }

    if(num1>=num2)//奇数大于偶数
    {
        map<int,int>::iterator it=mymap.begin();
        for(;it!=mymap.end();++it)
        {
            if(it->first%2==0)
            {
             //   cout<<it->second<<endl;
                res+=it->second;

            }
        }
    }
    else
    {
        map<int,int>::iterator it=mymap.begin();
        for(;it!=mymap.end();++it)
        {
            if(it->first%2)
            {
           //     cout<<it->second<<endl;
                res+=it->second;
            }
        }
    }

    cout<<res<<endl;
    return res;
    
       
    }
};
posted @ 2022-05-15 11:44  萧海~  阅读(22)  评论(0编辑  收藏  举报