435. 无重叠区间
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
if len(intervals) == 0: return 0
#sort using the right boundary
intervals.sort(key=lambda x: x[1])
#set up a count for non-overlapping
count = 1
#record the cut point
end = intervals[0][1]
#loop from index 1
for i in range(1, len(intervals)):
#if the cut point is smaller or equal to left boundary of
#current interval, we will have one more non-overlapping
if end <= intervals[i][0]:
count += 1
#renew the cut-point
end = intervals[i][1]
#since we need the interval we must remove, so do reduction
return len(intervals) - count
763.划分字母区间
class Solution(object):
def partitionLabels(self, s):
"""
:type s: str
:rtype: List[int]
"""
#build hashtable for 26 letter
hash = [0] * 26
#loop to look up every letter's appearance
for i in range(len(s)):
hash[ord(s[i]) - ord('a')] = i
result = []
left = 0
right = 0
for i in range(len(s)):
#renew right if the new letter has a larger range
right = max(right, hash[ord(s[i]) - ord('a')])
#if currently i = right,which means we have a parrtition meets req
if i == right:
#record result
result.append(right - left + 1)
#renew left so that we can record partition length
left = i+1
return result
56. 合并区间
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if len(intervals) == 0: return intervals
intervals.sort(key=lambda x: x[0])
result = []
result.append(intervals[0])
for i in range(1, len(intervals)):
#renew last
last = result[-1]
#if last right boundary is bigger or equal to current intervals
#renew last intervals as the bigger right boundary of cur and last
if last[1] >= intervals[i][0]:
result[-1] = [last[0], max(last[1], intervals[i][1])]
#else just append cur interval
else:
result.append(intervals[i])
return result
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
intervals.sort(key=lambda x:(x[0],x[1]))
result=[]
left=intervals[0][0]
right=intervals[0][1]
for i in range(1,len(intervals)):
if intervals[i][0]>right:
result.append([left,right])
left=intervals[i][0]
right=max(right,intervals[i][1])
else:
right=max(right,intervals[i][1])
result.append([left,right])
return result