[程序员] 大佬们,假设下面这个是已经排序过的关于时间的数组,现在需要添加到不同距离当前年份时间的数组,能用二分查找去实现吗?

public void test(){
String time2 = “2022-08-31”;
for(int i = 0; i<times.size();i++){
String time = times.get(i);
if(betweenMonth(time,time2) < 12){
oneYearTimes.add(time);
} else if(betweenMonth(time,time2) >= 12 && betweenMonth(time,time2) < 24 ){
one2twoYearTimes.add(time);
}
else if(betweenMonth(time,time2) >= 24 && betweenMonth(time,time2) < 36 ){
two2threeYearTimes.add(time);
}
else if(betweenMonth(time,time2) >= 36 && betweenMonth(time,time2) < 48 ){
three2fourYearTimes.add(time);
}
else if(betweenMonth(time,time2) >= 48 && betweenMonth(time,time2) < 48 ){
four2fiveYearTimes.add(time);
}
else if(betweenMonth(time,time2) >= 60 ){
moreThanFiveYearTimes.add(time);
}
}
}

static Long betweenMonth(String time1, String time2){ return ChronoUnit.MONTHS.between(parse(time1), parse(time2));
} static LocalDate parse(String str){ DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return LocalDate.parse(str, df);
}

发表回复

您的电子邮箱地址不会被公开。