算法训练营day31,贪心算法5

package main

import (

  "fmt"

  "sort"

)

//435. 无重叠区间

func eraseOverlapIntervals(intervals [][]int) int {

  if len(intervals) == 0 {

    return 0

  }

  count := 0 //移除数量

  //按第一位从小到大排序

  sort.Slice(intervals, func(i, j int) bool {

    return intervals[i][0] < intervals[j][0]

  })

  for i := 1; i < len(intervals); i++ {

    //如果当前左边界比前一个右边界比小,说明重叠需要删除

    if intervals[i][0] < intervals[i-1][1] {

      count++

      if intervals[i][1] > intervals[i-1][1] {

        intervals[i][1] = intervals[i-1][1]

      }

    }

  }

  return count

}

//763. 划分字母区间

func partitionLabels(s string) []int {

  m1 := make(map[byte]int)

  for i := 0; i < len(s); i++ {

    m1[s[i]] = i

  }

  result := make([]int, 0)

  left, right := 0, 0

  for i := 0; i < len(s); i++ {

    if m1[s[i]] > right {

      right = m1[s[i]]

    }

    if i == right {

      result = append(result, right-left+1)

      left = i + 1

    }

  }

  return result

}

//56. 合并区间

func merge(intervals [][]int) [][]int {

  result := make([][]int, 0)

  sort.Slice(intervals, func(i, j int) bool {

    return intervals[i][0] < intervals[j][0]

  })

  result = append(result, intervals[0])

  for i := 1; i < len(intervals); i++ {

    //如果当前左边界比结果数组最后一个右边界比小,说明重叠

    if intervals[i][0] <= intervals[i-1][1] {

      if result[len(result)-1][1] < intervals[i][1] {

        result[len(result)-1][1] = intervals[i][1]

      }

    } else {

      result = append(result, intervals[i])

    }

  }

  return result

}

你可能感兴趣的:(算法,贪心算法,go)