如何找到一个数被包含在数量的数组范围在java中 [英] How to find if a number is contained in an array of number ranges in java

查看:258
本文介绍了如何找到一个数被包含在数量的数组范围在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java对象的数组。

I have an array of java objects.


  • 每个对象存储定义一个数字范围内的两个多头。

  • 我已经有一个保证,在范围内的所有对象,数量范围不重叠。

我想快速查找阵列中的特定对象的,给定其可以(或可以不)落在数中的一个内的范围由对象定义的一个数。

I want a quick of finding a particular object in the array, given a number which may (or may not) fall within one of the number ranges defined by the objects.

我希望能做到这一点使用Array.binarySearch但看起来并不合适。

I was hoping to do this using Array.binarySearch but that doesn't look appropriate.

在做到这一点的最佳方式有什么想法?

Any thoughts on the best way to do this?

推荐答案

使用TreeMap中。最关键的是两个长域范围的较低;该值是对象

Use a TreeMap. The key is the lower of the two Long range bounds; the value is the object.

private TreeMap<Long, T> map = new TreeMap<Long, T>();

void insertObject(T object) {
    map.put(object, object.getLowerRangeBoundary());
}

T getObjectByKeyInRange(Long query) {
    // Get the first Object in the tree that corresponds with the query
    Map.Entry<Long, T> e = map.floorEntry(query);

    // If there's no entry, then the query value is lower than all ranges in the tree
    if (e == null) {
        return null;
    }

    T target = e.getValue();
    // "target" is the only object that can contain the query value
    // If the query value is within the range of "target", then it is our object
    if (query < target.getUpperRangeBoundary()) {
        return target;
    }

    // Nobody has the query value in their range; return null
    return null;
}

这篇关于如何找到一个数被包含在数量的数组范围在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆