Java书签 #区间合并算法与实际业务应用
Posted 有时有味
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java书签 #区间合并算法与实际业务应用相关的知识,希望对你有一定的参考价值。
1. 今日书签
力扣第56题,有个区间合并算法。类比可以实现时间区间重叠合并等业务场景。比如打卡时间、营业时间等等。
2. 解签方案
1)工具类:
public class IntervalMergeUtil
public static List<Interval> mergeStrArea(List<Interval> intervals)
List<Interval> result = new ArrayList<>();
// 校验入参是否为空,如果没有需要处理的区间参数,则直接返回
if (CollectionUtils.isEmpty(intervals))
return result;
// 根据start属性进行升序排序
Collections.sort(intervals, new Comparator<Interval>()
@Override
public int compare(Interval o1, Interval o2)
return o1.start.compareTo(o2.start);
);
// 这里用一个临时变量(temp)存储合并的interval
Interval temp = intervals.get(0);
for (int i = 1; i < intervals.size(); ++i)
if (intervals.get(i).start.compareTo(temp.end) <= 0)
if (temp.end.compareTo(intervals.get(i).end) < 0)
temp.end = intervals.get(i).end;
temp = new Interval(temp.start, temp.end);
else
result.add(temp);
temp = intervals.get(i);
result.add(temp);
return result;
@Data
@NoArgsConstructor
public static class Interval
String start;
String end;
Interval(String start, String end)
this.start = start;
this.end = end;
2)测试验证:
测试Demo:
public static void main(String[] args)
String str1 = "22:22";
String str2 = "20:22";
String str3 = "12:22";
System.out.println("22:22 晚于 20:22:" + str1.compareTo(str2) > 0);
System.out.println("12:22 晚于 20:22:" + str3.compareTo(str2) > 0);
List<Interval> intervals = new ArrayList<>();
Interval interval1 = new Interval("05:30", "12:00");
Interval interval2 = new Interval("11:30", "18:00");
Interval interval3 = new Interval("17:00", "23:00");
intervals.add(interval1);
intervals.add(interval2);
intervals.add(interval3);
List<Interval> intervalList = mergeStrArea(intervals);
System.out.println(JSON.toJSONString(intervalList));
List<Interval> intervals2 = new ArrayList<>();
Interval interval4 = new Interval("04:00", "08:30");
Interval interval5 = new Interval("08:00", "12:30");
Interval interval6 = new Interval("13:00", "18:00");
Interval interval7 = new Interval("18:00", "20:30");
Interval interval8 = new Interval("20:00", "23:55");
intervals2.add(interval4);
intervals2.add(interval5);
intervals2.add(interval6);
intervals2.add(interval7);
intervals2.add(interval8);
List<Interval> intervalList2 = mergeStrArea(intervals2);
System.out.println(JSON.toJSONString(intervalList2));
输出结果:
22:22 晚于 20:22:true
12:22 晚于 20:22:false
["end":"23:00","start":"05:30"]
["end":"12:30","start":"04:00","end":"23:55","start":"13:00"]
以上是关于Java书签 #区间合并算法与实际业务应用的主要内容,如果未能解决你的问题,请参考以下文章