【华为机考E卷】-“VLAN资源池”题解思路java

算法每一题,成长每一天~

C0E51 VLAN资源池

真题链接:【持续更新】2024华为 OD 机试E卷 机考真题库清单(全真题库)

思路

1、定义一个 Range(start, end) 对象,逐个验证,在范围内,则分割成两个(单点、端点 特殊处理)

Java

package com.ccr.paper_g;

import java.util.*;
import java.util.stream.Collectors;

public class C0E51 {

    static class Range {
        int start;
        int end;

        public Range(int start, int end) {
            this.start = start;
            this.end = end;
        }

        /**
         * 单点,且等值
         */
        public boolean pointEqual(int v) {
            return start == end && v == start;
        }

        /**
         * 区间内
         */
        public boolean inRange(int v) {
            return v >= start && v <= end;
        }

        @Override
        public String toString() {
            return start == end
                    ? "" + start
                    : start + "-" + end;
        }
    }

    static final List<Range> LIST = new ArrayList<>();
    static final List<Range> APPEND_LIST = new ArrayList<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        String[] split = in.nextLine().split(",");
        for (String s : split) {
            if (s.contains("-")) {
                String[] split1 = s.split("-");
                LIST.add(new Range(Integer.parseInt(split1[0]),
                                   Integer.parseInt(split1[1])));
            } else {
                LIST.add(new Range(Integer.parseInt(s), Integer.parseInt(s)));
            }
        }

        int v = in.nextInt();

        Iterator<Range> iterator = LIST.iterator();
        while (iterator.hasNext()) {
            if (check(v, iterator.next())) {
                iterator.remove(); // 移除原本的区间
                break;
            }
        }
        LIST.addAll(APPEND_LIST); // 加入新分割的区间
        LIST.sort(Comparator.comparingInt(o -> o.start));

        String print = LIST.stream()
                           .map(Range::toString)
                           .collect(Collectors.joining(","));
        System.out.println(print);
    }

    static boolean check(int v, Range r) {
        if (r.pointEqual(v)) {
            return true;
        } else if (r.inRange(v)) {
            if (v == r.start) {
                APPEND_LIST.add(new Range(r.start + 1, r.end));
            } else if (v == r.end) {
                APPEND_LIST.add(new Range(r.start, r.end - 1));
            } else {
                APPEND_LIST.add(new Range(r.start, v - 1));
                APPEND_LIST.add(new Range(v + 1, r.end));
            }
            return true;
        }

        return false;
    }
}


总结

~


算法要多练多练多练!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值