Leetcode (12) insert interval

Time:2022-8-2

Title:

Give a non overlapping interval list sorted by the beginning and end of the interval.

To insert a new interval into the list, you need to ensure that the intervals in the list are still orderly and do not overlap (you can merge the intervals if necessary).

Idea:

First, through analysis, we can find that there are three kinds of intervals. One is on the left side of the insertion interval, that is, the right interval is smaller than the left interval of the insertion interval. The other is on the right side of the insertion interval, that is, the left interval is larger than the right interval of the insertion interval. The above two kinds of intervals can be directly inserted into the new area, and the last one is the intersection with the insertion interval, which needs to be merged. Next is the code implementation:
Leetcode (12) insert interval

func insert(intervals [][]int, newInterval []int) [][]int {
   left,right := newInterval[0],newInterval[1]
   Var isinserted = false // used to determine whether the interval has been inserted. False means it has not been inserted, and true means it has been inserted
 var ans [][]int
 //1. Read the interval from left to right. If it does not intersect with the interval, insert it directly
 //2. If it intersects with the interval, update the value of the interval and continue to judge
 //3. If the reading is completed, or the first value that does not intersect with the interval is read, insert the interval
 //4. Insert the new array directly into the inserted interval
 for _,val := range intervals{
      if isInserted{
         ans = append(ans,val)
         continue
 }
      if val[0]>right && !isInserted{
         ans = append(ans,[]int{left,right})
         isInserted = true
 ans = append(ans,val)
         continue
 }
      if val[1]<left && !isInserted{
         ans = append(ans,val)
         continue
 }
      left = min(left,val[0])
      right = max(right,val[1])
   }
   if !isInserted{ans = append(ans,[]int{left,right})}
   return ans
}
func max(x,y int)int{
   if x>y{
      return x
   }
   return y
}
func min(x,y int)int{
   if x<y{
      return x
   }
   return y
}

Leetcode (12) insert interval