我有BookingDateRange的一個List,BookingDateRange是:要查找所有日期從給定的列表中重疊的日期範圍的範圍
public class BookingDateRange {
private Date fromDate;
private Date toDate;
//getters & setters of properties
}
要求:
- 我需要找到如果有的話日期重疊在BookingDate列表中說dateRangeList
- 如果是,找到所有重疊的日期範圍對say字符串列表說overlapDatePairs
例1:
輸入1:
dateRangeList [0] = 23 12 2012- 2012年12月27日
dateRangeList [1] =二〇一二年十二月一十四日 - 2012年12月25日
dateRangeList [2] = 1 jan 2012 - 23 jan 2012
輸出1:
個isOverlappingDates =真
overlappingDatePairs = [0_1]
例2:
輸入2:
dateRangeList [0] = 23 12 2012- 2012年12月27日
dateRangeList [1] = 1月2012年 - 23月2012
輸出2:
isOverlappingDates =假
overlappingDatePairs = []
我的解決方案:
/**
* 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上遇到過幾個解決方案。但是他們都不能完全滿足這個要求。
感謝, Shikha
貌似複雜度爲O(N^2)不O(2^N)**編輯**:d – gtgaxiola
@gtgaxiola糟糕..錯字..是..爲O(n^2)。在問題中編輯。 –