container/heap簡介
container/heap提供了具有堆序性質的基本框架,只需要實現響應的接口,便可獲得一個優先隊列
接口如下:
type Interface interface { sort.Interface Push(x interface{}) // add x as element Len() Pop() interface{} // remove and return element Len() - 1. }
其中,sort.Interface接口如下
type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) }
實踐
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.
Example 1:
Input: ["23:59","00:00"] Output: 1
Note:
- The number of time points in the given list is at least 2 and won't exceed 20000.
- The input time is legal and ranges from 00:00 to 23:59.
分析:求最短時間差,也就是說把00:00到23:59的分鐘數從[0,24*60-1]的順序排列起來並首尾相接,最短時間差只能出現在相鄰的兩個時間點;
相鄰的兩個時間點之差有兩種情況:
1.兩個點都在一天內:從小時間點到大時間點,next-pre<12*60,也就是小於[0,24*60-1]組成的圈的一半,此值可能爲最小值
2.兩個點跨越00:00,小值在大值的後一天:24*60+pre-next可能爲最小值
因此我們可以先把給定的時間排序,然後依次求出相鄰兩個時間點之間最小差值,返回最小值即可
實現步驟就是,先實現一個優先隊列,將數據入隊,然後依次出隊並計算差值
代碼
type StrHeap []string // 使用字符串切片來存儲數據,並實現heap的相關接口 func (h StrHeap) Len() int { return len(h) } func (h StrHeap) Less(i, j int) bool { return h[i] < h[j] } func (h StrHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *StrHeap) Push(x interface{}) { *h = append(*h, x.(string)) } func (h *StrHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0: n-1] return x } func findMinDifference(timePoints []string) int { h := StrHeap(timePoints) heap.Init(&h) // 初始化堆 ret := 24 * 60 pre := timeToInt(heap.Pop(&h).(string)) first:=pre next:=24 * 60 for h.Len() > 0 { // 依次取出每個值,求差 next = timeToInt(heap.Pop(&h).(string)) tmp := next - pre if tmp>12*60{ tmp=24*60-tmp } if tmp < ret { ret = tmp } pre = next } // 最值有可能爲首尾的差 tmp := next - first if tmp>12*60{ tmp=24*60-tmp } if tmp < ret { ret = tmp } return ret } //將字符串時間轉換爲分鐘數,用以計算差值 func timeToInt(t string) int { fmt.Println(t) arr := strings.Split(t, ":") hour, _ := strconv.Atoi(arr[0]) minute, _ := strconv.Atoi(arr[1]) return hour*60 + minute }
測試
func TestFindMinDifference(t *testing.T) { arr := []string{"08:01", "00:17", "14:12", "12:44", "06:06"} ret := findMinDifference(arr) fmt.Println(ret) }