BookingDateRangeのリストがあります。BookingDateRangeは次のとおりです。
public class BookingDateRange {
private Date fromDate;
private Date toDate;
//getters & setters of properties
}
要件:
- BookingDateのリストでdateRangeListと言う日付が重複していないかどうかを確認する必要があります
- はいの場合、重複するすべての日付範囲のペアを検索します。たとえば、文字列のリストは、overlapingDatePairsと言います。
例1:
入力1:
dateRangeList [0]=2012年12月23日-2012年12月27日
dateRangeList [1]=2012年12月14日-2012年12月25日
dateRangeList [2]=2012年1月1日-2012年1月23日
出力1:
isOverlappingDates = true
重複する日付ペア=[0_1]
例2:
入力2:
dateRangeList [0]=2012年12月23日-2012年12月27日
dateRangeList [1]=2012年1月1日-2012年1月23日
出力2:
isOverlappingDates = false
重複する日付ペア=[]
私の解決策:
/**
* Checks if any of the dates overlap.
*
* @param dateRangeList the date range list
* @param overlappingDatePairs the overlapping date pairs where overlappingDatePair is stored in the format dateRange1_dateRange2
* @return true, if any of the dates overlap.
*/
public static boolean isOverlappingDates(
List<BookingDateRange> dateRangeList,
List<String> overlappingDatePairs) {
boolean isOverlap = false;
for (int index1 = 0; index1 < dateRangeList.size(); index1++) {
for (int index2 = index1 + 1; index2 < dateRangeList.size(); index2++) {
// Overlap exists if (StartA <= EndB) and (EndA >= StartB)
Date startA = dateRangeList.get(index1).getFromDate();
Date endA = dateRangeList.get(index1).getToDate();
Date startB = dateRangeList.get(index2).getFromDate();
Date endB = dateRangeList.get(index2).getToDate();
boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;
boolean isCurrentPairOverlap = false;
isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;
if (isCurrentPairOverlap) {
overlappingDatePairs.add(index1 + "_" + index2);
isOverlap = true;
}
}
}
return isOverlap;
}
このアプローチの複雑さはO(n ^ 2)です。より複雑にすることは可能ですか?より複雑なアルゴリズムに到達できませんでした。
SOでいくつかの解決策に出くわしました。しかし、それらのどれも完全に要件を満たすことができませんでした。
ありがとう、シカ