Interval Selection

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/82688339

https://www.hackerrank.com/challenges/interval-selection/problem

按end排序,然后从end大的开始遍历每个interval,先判断到当前interval的end,有哪些interval的start已经比这个end大,说明这个interval一定跟自后要遍历的interval没有交集。

然后维护一个大小为2的数组表示当前还处于"开状态"的interval,如果这个数组填满还要填一个,就删掉start最小的那个interval

ref:https://www.hackerrank.com/challenges/interval-selection/forum/comments/220810

this can be solved in O(nlogn) with greedy algo. Sort all the end points, then iterate through all the end points using a simple array of size 2 to keep track of the intervals that are still open(haven't met their closing point yet). Whenever the opening intervals reached 3, just remove the interval that spans the furtherst.


def intervalSelection(intervals):
    intervals.sort(key=lambda a:-a[1])
    res,cnt=2,0
    open=[-1]*2
    for i in range(len(intervals)):
        if open[0]!=-1 and intervals[open[0]][0]>intervals[i][1]: open[0]=-1
        if open[1]!=-1 and intervals[open[1]][0]>intervals[i][1]: open[1]=-1
        if open[0]!=-1 and open[1]!=-1:
            if intervals[i][0]<=min(intervals[open[0]][0],intervals[open[1]][0]):
                continue
            else:
                if intervals[open[0]][0]<intervals[open[1]][0]: open[0]=i
                else: open[1]=i
        else:
            if open[0]==-1: open[0]=i
            else: open[1]=i
            cnt+=1
            res=max(res,cnt)
    return res

if __name__ == '__main__':
    s = int(input())
    for s_itr in range(s):
        n = int(input())
        intervals = []
        for _ in range(n):
            intervals.append(list(map(int, input().rstrip().split())))
        result = intervalSelection(intervals)
        print(result)
            
        
        

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/82688339