📑 题目:56. 合并区间

🚀 本题 LeetCode 传送门

题目大意

合并给的多个区间,区间有重叠的要进行区间合并。

解题思路

先按照区间起点进行排序。然后从区间起点小的开始扫描,依次合并每个有重叠的区间。

代码

  1. package leetcode
  2. /**
  3. * Definition for an interval.
  4. * type Interval struct {
  5. * Start int
  6. * End int
  7. * }
  8. */
  9. // Interval define
  10. type Interval struct {
  11. Start int
  12. End int
  13. }
  14. func merge56(intervals []Interval) []Interval {
  15. if len(intervals) == 0 {
  16. return intervals
  17. }
  18. quickSort(intervals, 0, len(intervals)-1)
  19. res := make([]Interval, 0)
  20. res = append(res, intervals[0])
  21. curIndex := 0
  22. for i := 1; i < len(intervals); i++ {
  23. if intervals[i].Start > res[curIndex].End {
  24. curIndex++
  25. res = append(res, intervals[i])
  26. } else {
  27. res[curIndex].End = max(intervals[i].End, res[curIndex].End)
  28. }
  29. }
  30. return res
  31. }
  32. func max(a int, b int) int {
  33. if a > b {
  34. return a
  35. }
  36. return b
  37. }
  38. func min(a int, b int) int {
  39. if a > b {
  40. return b
  41. }
  42. return a
  43. }
  44. func partitionSort(a []Interval, lo, hi int) int {
  45. pivot := a[hi]
  46. i := lo - 1
  47. for j := lo; j < hi; j++ {
  48. if (a[j].Start < pivot.Start) || (a[j].Start == pivot.Start && a[j].End < pivot.End) {
  49. i++
  50. a[j], a[i] = a[i], a[j]
  51. }
  52. }
  53. a[i+1], a[hi] = a[hi], a[i+1]
  54. return i + 1
  55. }
  56. func quickSort(a []Interval, lo, hi int) {
  57. if lo >= hi {
  58. return
  59. }
  60. p := partitionSort(a, lo, hi)
  61. quickSort(a, lo, p-1)
  62. quickSort(a, p+1, hi)
  63. }