当前位置:网站首页>力扣解法汇总1217-玩筹码
力扣解法汇总1217-玩筹码
2022-07-22 08:55:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:力扣
描述:
有 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-cost-to-move-chips-to-the-same-position
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
* 解题思路: * 这题比较简单,我们只需要记录奇数位置数量和偶数位置数量即可。 * 1挪动到2需要cost1,1挪到4也需要cost1。所以一个数挪到任意位置,只需要cost=0或1。 * 总结一下,就是奇数位置挪到偶数位置需要cost1,挪到奇数位置cost0。 * 所以,我们只要统计更少的那一组,挪更少的那一组即可。
代码:
public class Solution1217 {
public int minCostToMoveChips(int[] position) {
int evenNum = 0;
int oddNum = 0;
for (int i = 0; i < position.length; i++) {
int value = position[i];
if (value % 2 == 0) {
oddNum++;
} else {
evenNum++;
}
}
return Math.min(evenNum, oddNum);
}
}
边栏推荐
- 基于细粒度嵌入空间预留的密文域图像可逆信息隐藏方法
- "Review of software engineering in Wuhan University of technology" Chapter 6 | coding specification
- QT笔记——QTableWidget表格生成树,QTreeWidget树节点生成表格内容
- [exception] generate guid and datetime, import test data to the database
- Applet sorted by an element of the structure (fishing_3)
- 需要达到什么水平,程序员才能顺利拿到20k月薪无压力?
- double类型不能进行精确计算的问题
- SQL多条件查询无法实现
- Gbase8s database set connection statement
- Understand relevant concepts of prosody. XMPP, jabber, bosh, etc
猜你喜欢
A trick to teach you how to visualize recruitment data ~ is there anyone who can't analyze these data cases?
QT notes - operation EXECL
double类型不能进行精确计算的问题
Concurrent model values actor and CSP
「武汉理工大学 软件工程复习」第二章 | 软件过程模型
"Review of software engineering in Wuhan University of technology" Chapter 2 | software process model
Thread learning notes
Fcntl function
QT笔记——网络通信 之 QUdpSocket
C#入门系列(二十七) -- LINQ简析
随机推荐
力扣解法汇总731-我的日程安排表 II
double类型不能进行精确计算的问题
[exception] generate guid and datetime, import test data to the database
MySQL密码正确但是启动报错Unable to create initial connections of pool.Access denied for user ‘root‘@‘localhost
Go concurrent programming - work pool
Learn TB writing method with SPI simulation file
Simplify the complexity and talk about the abstraction of replication state machine system architecture
QT笔记——自定义数据类型
Use of bullets in object pool mode in aircraft war
女嘉賓報名
Verilog for loop (1)
vmware虚拟机和vsphere相互迁移
QT notes - drag lines and movement of qtablewidget
Mutexes and semaphores
Yunyuanyuan (10) | introduction to kubernetes in kubernetes
线程学习笔记
文件描述符的复制
SQL设计教学管理库
Female guest registration
Copy of file descriptor