题目要求:
- 给出一个数组nums,你需要通过交换位置,将数组中 任何位置 上的 小于 k 的整数 组合到一起,并返回所有可能中所需最少的交换次数。
- 输出将数组A中小于k的整数组合到一起的最小交换次数。
- 组合在一起是指满足条件的数字相邻,不要求在数组中的位置相邻。
主要想法:
滑动窗口的思想
根据终点状态(交换后,1 都连在一起),逆推检查过程,所有 1 连在一起就意味着「原数组中 k 个 1」刚好可以让数组中长度为 k 的子数组的和为 k
- (使用前缀和可快速得到所有长度为 k 的区域中的数值之和 sum,k - sum 即为移动次数)
- 或者 :统计窗口中0的个数即为交换的次数
代码:
var minChange = function (nums, k) {
// count表示符合条件的1的个数, index为存放符合条件位置的数组,times为最少交换次数
let count = 0, index = [], times = Infinite;
// 遍历nums得到index数组和count
for(let i = 0; i < nums.length; i++) {
if (nums[i] < k) {
count++;
index[i] = 1;
}
}
// 当全都不符合或者全都符合条件,最少交换次数0
if (!index.length || count === nums.length) return times;
// 此处利用滑动窗口思想,拿到当前位置将数据组合在一起所需交换次数changeTime,
// 将它和times作比较,取最小交换次数
for(let i = 0; i < index.length - count; i++) {
// 1. count - sum;
let changeTime = count - index.slice(i, count).reduce((a, b) => a+b);
// 或者 :统计窗口中0的个数即为交换的次数
// let changeTime = 0;
// for(let j of index.slice(i, count)) {
// !j ? changeTime++ : null;
// }
times = Math.min(changeTime, times);
}
return times;
}
console.log(minChange([1,3,1,4,0], 2))