生活日用算法——java 区间重叠判断
百度后看了一些解法,效率虽可能比较高,但相对代码太复杂,不便于阅读与代码交接,自己写了下,方法如下。
方法一:
private void checkOverlap(LinkedList<ActiveExtendDTO> activeExtendDOList) { activeExtendDOList.sort(Comparator.comparing(ActiveExtendDTO::getCommodityMinNum)); Long temp = activeExtendDOList.poll().getCommodityMaxNum(); for (ActiveExtendDTO activeExtend : activeExtendDOList) { if (temp >= activeExtend.getCommodityMinNum()) { throw new Exception("区间有重叠"); } temp = activeExtend.getCommodityMaxNum(); } }
方法二(1.8):
private void checkOverlap2(List<ActiveExtendDTO> list) { list.stream().sorted(Comparator.comparing(ActiveExtendDTO::getCommodityMinNum)) .reduce((a, b) -> { if (a.getCommodityMaxNum() >= b.getCommodityMinNum()) { throw new Exception("区间有重叠"); } return b; }); }
附ActiveExtendDTO类:
@Data public class ActiveExtendDTO { @ApiModelProperty(value = "最小数量") @NotBlank(message = "最小数量不可为空") private Long commodityMinNum; @ApiModelProperty(value = "最大数量") @NotBlank(message = "最大数量不可为空") private Long commodityMaxNum; }