The "Beauty of programming" interval coincidence judgment

Source: Internet
Author: User

Given a source interval [x, y] (y>=x) and n unordered target range [x1,y1] [x2,y2] [x3,y3] [Xn,yn], determine if the source range [x, Y] is within the target range?

For example: Given the source interval [1,6] and a set of unordered target intervals [2,3] [[3,9]], the interval [1,6] is considered to be within the interval [2,3] [+] [3,9] (since the target range is actually [1,9]).

Analysis and Solution

Method One: Direct method

A more straightforward idea is to project the source and target intervals onto the axes, and only examine the parts of the source range that are not covered. If all of the intervals are projected and the source range is still not covered, then the source range is not within the target range.

The time complexity is O (N2).

Method Two: Sort the merge target interval

The target interval is combined into several ordered intervals so that the interval can be compared.

Before merging, the intervals are sorted by x-coordinate and then merged into disjoint intervals.

After merging, it is possible to traverse the combined interval to determine whether the source interval is within the combined interval, or it can be determined by a binary search method.

The time complexity is O (NLOGN).

Scaling Issues

How to deal with the coverage problem of two-dimensional space? For example, there are a number of Windows on the desktop, how to tell if a window is completely covered by another window?

The "Beauty of programming" interval coincidence judgment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.