最小交换次数
描述
给出数字K,请输出所有结果小于K的整数组合到一起的最少交换次数。
组合一起是指满足条件的数字相邻,不要求相邻后在数组中的位置。
示例1:
输入
1 3 1 4 0
2
输出
1
说明:
小于2的表达式是1 1 0, 共三种可能将所有符合要求数字组合一起,最少交换1次
示例2:
输入
0 0 0 1 0
2
输出
0
示例3:
输入
2 3 2
1
输出
0
法一:
import java.util.*;
public class Main {
public static void main(String[] args) {
//首先把接收到的字符串转化为int数组
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String[] str = sc.nextLine().split("\\s");
int target = sc.nextInt();
int[] arr = new int[str.length];
int totalLess = 0;
for (int i = 0 ; i < arr.length ; i++) {
arr[i] = Integer.parseInt(str[i]);
if (arr[i] < target) {
totalLess++;
}
}
//有一个滑动窗口,窗口大小固定为小于target的数,然后但凡在窗口内不小于的,就是需要交换的
int res = Integer.MAX_VALUE;
for (int i = 0 ; i < arr.length + 1 - totalLess ; i++) {
int count = 0;
for (int j = 0 ; j < totalLess ; j++) {
if (arr[i + j] > target) {
count++;
}
}
res = Math.min(res, count);
}
System.out.println(res);
}
}
}