Daily Coding Problem: Problem #723

/**
 * This problem was asked by Google.
Given a set of closed intervals, find the smallest set of numbers that covers all the intervals.
If there are multiple smallest sets, return any of them.
For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9],
one set of numbers that covers all these intervals is {3, 6}.
 * */
class Problem_723 {
    /*
    * solution: find out the maximum in left of intervals and minimum in right of intervals,
    * Time complexity:O(n), Space complexity:O(1)
    * */
    fun smallestSet(intervals: Array<IntArray>): IntArray {
        if (intervals == null || intervals.isEmpty()) {
            return intArrayOf()
        }
        var smallMax = Int.MAX_VALUE
        var largeMin = Int.MIN_VALUE
        for (interval in intervals) {
            largeMin = Math.max(largeMin, interval[0])
            smallMax = Math.min(smallMax, interval[1])
        }
        return intArrayOf(smallMax, largeMin)
    }
}

 

posted @ 2020-11-25 10:45  johnny_zhao  阅读(65)  评论(0编辑  收藏  举报