GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/057_Insert_Interval.py at master · jimx33/leetcode

Expand file tree

/

057_Insert_Interval.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
48 lines (43 loc) · 1.5 KB
/

057_Insert_Interval.py

Copy path

File metadata and controls

48 lines (43 loc) · 1.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
if intervals is None or len(intervals) == 0:
return [newInterval]
intervals.sort(key=lambda x:x.start)
pos = 0
while pos < len(intervals):
# left of pos
if newInterval.end < intervals[pos].start:
intervals.insert(pos, newInterval)
return intervals
# overlap with pos
if self.check_overlap(intervals[pos], newInterval):
temp = intervals.pop(pos)
newInterval = self.merge_intervals(temp, newInterval)
else:
pos += 1
if len(intervals) == 0 or pos == len(intervals):
intervals.append(newInterval)
return intervals
def check_overlap(self, curr_int, new_int):
if curr_int.start <= new_int.start:
if curr_int.end > new_int.start:
return True
else:
if curr_int.start <= new_int.end:
return True
return False
def merge_intervals(self, int1, int2):
temp_int = Interval()
temp_int.start = min([int1.start, int2.start])
temp_int.end = max([int1.end, int2.end])
return temp_int
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.