Interview Question 7: Insert Intervals

Question: Given a sequence of intervals that does not overlap, insert a new interval into the sequence, requiring that no overlap be maintained. Assuming that the intervals stored in the series are ordered, the interval definition is as in the title "Number of overlapping intervals".

Example:

    Suppose we have two non-overlapping and sorted intervals: [1,5], [6,10], now insert a new interval [4,6], then the final result is [1,10].


Code:

package main
 
 
import (
    "fmt"
)
 
 
typeIntervalstruct{   
    startint 
    endint   
}
 
 
// Simulating the process in the brain and on paper will help understanding
func insert(intervals []Interval, newInt Interval) Interval {
    n  := len (intervals) 
    if n ==0{  
        return newInt
    }
    i :=0 
    // Find the position to be inserted, that is, determine the starting value of the interval 
    for i < n && newInt.start > intervals[i].end {
        i +=1 
    }
    // find the end value of the interval 
    for i < n && newInt.end > intervals[i].start {
        if newInt.start > intervals[i].start {
            newInt.start = intervals[i].start
        }
        if newInt.end < intervals[i].end {
            newInt.end = intervals[i].end
        }
        i +=1 
    }
    return newInt
}
 
 
func main() {
    // test case 
    a := []Interval{Interval{1,2},Interval{5,6},Interval{8,10},Interval{20,30}}       
    fmt.Println(insert(a, Interval{5,9})) 
}
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325782555&siteId=291194637