OD华为机试 9

最小交换次数

描述

给出数字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);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值