How to find if a point is within a set of intervals?

老子叫甜甜 提交于 2019-12-03 13:56:05

Hm, maybe you can use an interval or a segment tree:

If you have the integers ranges sorted and the ranges are non-overlapping, you can perform binary search to find the correct range in logarithmic time.

Are there any constraint on the range? Based on that you can probably come up with hashing function to search in constant time. But this depends on how your constraints are.

After reflexion, I think that the following code should work in logarithmic time, excluding the time needed to build the map:

enum pointType {
    point,
    open,
    close
};
std::map<long int, pointType> mapPoints;

mapPoints.insert(std::pair<long int, pointType>(3, point));

//create the 5:10 interval:
mapPoints.insert(std::pair<long int, pointType>(5, open));
mapPoints.insert(std::pair<long int, pointType>(10, close));

int number = 4;
bool inside = false;
std::map<long int, pointType>::iterator it1 = mapPoints.lower_bound(number);

if(it1->first == number || it1->second == close) {
    inside = true;
}

I think this should work as long as the map is filled properly with non-overlapping intervals

First check a hash_map of points. That's the simple check.

Then simply order a map of intervals by the first coordinate and then find lower_bound of the point.

Then check if you are contained in the element returned. If you aren't in that, you aren't in any.

You could do that in sublinear time GIVEN a tree data structure (I'd recommend a B-tree),if you don't count the time taken to build the tree (most trees take n log n or similar time to build).

If you just have a plain list, then you cannot do better than linear because in the worst case you potentially have to check all points and intervals.

You can use a Bloom Filter to test a point and see if it's not in an interval, in linear O(1) time. If it passes that test you must use another method such as a binary search to see if it's definitely part of an interval, in O(log n) time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!