题目
有 n 个筹码。第 i 个筹码的位置是 position[i] 。
我们需要把所有筹码移到同一个位置。在一步中,我们可以将第 i 个筹码的位置从 position[i] 改变为:
position[i] + 2 或 position[i] - 2 ,此时 cost = 0
position[i] + 1 或 position[i] - 1 ,此时 cost = 1
返回将所有筹码移动到同一位置上所需要的 最小代价 。
- 来源:力扣(LeetCode)
- 链接:leetcode.cn/problems/mi…
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
思路
把每个position[i] 都遍历一遍,每个position[j]移动到position[i]的最小成本可以计算出来,这样就可以得到 最终的最小成本。
代码
class Solution {
public int minCostToMoveChips(int[] position) {
int min = position.length;
int cost = 0;
for (int i = 0; i < position.length; i++) {
cost = 0;
for (int j = 0; j < position.length; j++) {
if (position[i] == position[j]) {
continue;
}
int t = Math.abs(position[i] - position[j]);
if ((t & 1) != 0) {
cost++;
}
}
min = Math.min(min, cost);
}
return min;
}
}
复杂度
- 时间复杂度:O(n^2)
- 空间复杂度:O(1)
解法二
思路
所有奇数位置移动到奇数位置的最小代价是0;所有偶数位置移动到偶数位置的最小代价是0。
只有奇数位置移动到偶数位置或者相反才会消耗代价1。
那么总共的最小代价就是 min(奇数位置的个数,偶数位置的个数)
代码
class Solution {
public int minCostToMoveChips(int[] position) {
int odd = 0;
int even = 0;
for (int i = 0; i < position.length; i++) {
if ((position[i] & 1) != 0) {
odd++;
} else {
even++;
}
}
return Math.min(odd, even);
}
}