Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the merging interval problem by LeetCode

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report