gpt4 book ai didi

java - 结合 2 个间隔

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:35 25 4
gpt4 key购买 nike

给定 2 个具有 int start、int end 和 boolean status 的区间,组合这 2 个区间,如下所示

i1 和 i2 是 2 ArrayList<Intreval>和 res 应包含组合间隔的输出。

例子:

-INF --------- 6 ------- 10 --------- 30 --------- INF

F T T F

-INF --- 5 ------------------- 20 --------- 35 ---- INF

T T F F

输出:

-INF ---5 ---- 6 -------- 10 -- 20 ---- 30 -- 35 --- INF

F F T T F F F

代码创建了 i1 和 i2,它们是 ArrayList<Intervals> .
i1 has [[-INF,6,false],[6,10,true],[10,30,true],[30,INF,false]]
i2 has [[-INF,5,true],[5,20,true],[20,35,false],[35,INF,false]]
res should contain [[-INF,5,false],[5,6,false],[6,10,true],[10,20,true],[20,30,false],[30,35,false],[35,INF,false]]

代码:

Class Interval
{
int start;
int end;
boolean status;
public Interval(int start, int end, boolean status)
{
this.start = start;
this.end = end;
this.status = status;
}
}
class MyCode {
public static void main (String[] args) {
ArrayList<Interval> i1 = new ArrayList<Interval>();
i1.add(new Interval(Integer.MIN_VALUE, 6, false));
i1.add(new Interval(6,10,true));
i1.add(new Interval(10,30,true));
i1.add(new Interval(30,Integer.MAX_VALUE,false));

ArrayList<Interval> i2 = new ArrayList<Interval>();
i2.add(new Interval(Integer.MIN_VALUE, 5, true));
i2.add(new Interval(5,20,true));
i2.add(new Interval(20,35,false));
i2.add(new Interval(35,Integer.MAX_VALUE,false));

int i=0, j=0;
ArrayList<Interval> res = new ArrayList<Interval>();
}
}

最佳答案

区间覆盖所有轴,所以我们可以只考虑左端和 T/F 场。

末端已排序,因此应用合并过程(就像合并排序中的那样)。

 ia = 0
ib = 0
//Start the first output interval code

while ia < ACount and B < BCount
if A[ia].Position <= B[ib].Position
ia++
AActive = True
else if A[ia].Value >= B[ib].Value //reuse == case for simplicity
// and incrementing both indexes
ib++
AActive = False

State = A[ia].BooleanField && B[ib].BooleanField
Pos = A[ia].Position if AActive else B[ib].Position
CloseOutputInterval(Pos)
StartOutputInterval(Pos, State)

continue with the rest (A or B left)

关于java - 结合 2 个间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com