Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the merging interval problem by LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:15:21 09月20日 Update

Editor to share with you LeetCode how to solve the merger interval problem, I hope you will learn something after reading this article, let's discuss it together!

Topic description:

"given an interval, merge the overlapping parts (the input intervals are not in order)"

For example:

Input: [[1,3], [2,6], [8,10], [15,18]] output: [[1,6], [8,10], [15,18]] input: [[1,4], [0,0]] output: [[0,0], [1,4]]

The first attempt

1. First of all, the input two-dimensional array is sorted according to the size of the first element, so that the later judgment can be made.

two。 Set a final returned array: final_list = []

3. Set a cursor array (the layer in the two-dimensional array): final_interval=intervals [0]

Set it directly to the first array element of the sorted input array, and then compare it in turn

Final_interval is compared with the array in the input two-dimensional array in turn:

The right endpoint of final_interval > = the left endpoint of the comparison array: there is overlap

(1) the right end point of final_interval takes the larger of the two right end points

(2) the left endpoint of final_interval is smaller than that of both.

No overlap:

Add final_interval to final_list and set final_interval to the next array

Beautify the code.

The if judgment that the right endpoint is equal to the left endpoint can be removed (may not be used)

Use built-in functions max and min to take large endpoints and small endpoints

Summary

Any topic should first judge the situation that the input is empty.

Two-dimensional array is realized by append (array) of array.

Anonymous functions are used in array sorting

Intervals.sort (key=lambda x: X [0]) after reading this article, I believe you have some understanding of "how to solve the merger interval problem in LeetCode". If you want to know more about it, please follow the industry information channel. Thank you for reading!

Tags: Arrays endpoints inputs intervals two dimensions questions elements functions articles topics sorting output no small and medium code place size done summary situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia OPPO Reno Shulou Tech Info Shulou Technology Microsoft