java 区间_java整数区间

import com.google.common.collect.Lists;

import lombok.Getter;

import lombok.Setter;

import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;

import java.util.Collection;

import java.util.Collections;

import java.util.List;

/**

* 功能描述: 用于表达连续的整数区间

*

* @author : yuanchao.he

* @version 1.0 2017-04-06

*/

@Getter

@Setter

public class LocalRange implements Serializable {

private int lowerRange;

private int upperRange;

public LocalRange(int lowerRange, int upperRange) throws Exception {

if (lowerRange > upperRange) {

throw new Exception(

"invalid range number, upperRange must greater or equal to lowerRange");

}

this.lowerRange = lowerRange;

this.upperRange = upperRange;

}

private LocalRange() {}

/**

* 单个区间内是否包含特定的整数

* @param current

* @return

*/

public boolean contains(final int number) {

return this.lowerRange <= number && number <= this.upperRange;

}

/**

* 一组区间内是否包含特定的整数

* @param ranges

* @param number

* @return

*/

public static boolean contains(final List ranges, final int number){

return binarySearch(ranges, number)!=null;

}

/**

* 采用二分查找的方式来查询

* @param ranges

* @param number

* @return

*/

public static LocalRange binarySearch(List ranges, int number) {

if (CollectionUtils.isEmpty(ranges)) {

return null;

}

int from = 0;

int to = ranges.size() - 1;

while (from <= to) {

int middle = (to - from) / 2 + from;

if (ranges.get(middle).contains(number)) {

return ranges.get(middle);

}

if (ranges.get(middle).getUpperRange() < number) {

from = middle + 1;

}

if (ranges.get(middle).getLowerRange() > number) {

to = middle - 1;

}

}

return null;

}

/**

* 将集合中的整数转化为一组区间

* @param collection

* @return

*/

public static List fromCollection(Collection collection) {

if (CollectionUtils.isEmpty(collection)) {

return Collections.emptyList();

}

List numbers = Lists.newArrayList(collection);

Collections.sort(numbers);

List ranges = Lists.newArrayList();

int lowerRange = numbers.get(0);

int upperRange = numbers.get(0);

for (int index = 1; index < numbers.size(); index++) {

if ((upperRange + 1) == numbers.get(index)) {

upperRange = numbers.get(index);

} else {

ranges.add(LocalRange.init(lowerRange, upperRange));

lowerRange = numbers.get(index);

upperRange = lowerRange;

}

}

ranges.add(LocalRange.init(lowerRange, upperRange));

return ranges;

}

private static LocalRange init(int lowerRange, int upperRange) {

LocalRange localRange = new LocalRange();

localRange.lowerRange = lowerRange;

localRange.upperRange = upperRange;

return localRange;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值