优化算法

This commit is contained in:
Hami Lemon 2022-03-28 20:04:51 +08:00
parent 8891c44211
commit 8b57abe8ee

52
srt.go
View file

@ -6,7 +6,6 @@ import (
"github.com/Hami-Lemon/lrc2srt/glist" "github.com/Hami-Lemon/lrc2srt/glist"
"io" "io"
"os" "os"
"sort"
"strconv" "strconv"
"strings" "strings"
) )
@ -109,27 +108,44 @@ func (s *SRT) Merge(other *SRT, mode SRTMergeMode) {
} }
} }
//todo 改进算法,现在的算法太慢了 //可以类比为合并两个有序链表,
//算法参考:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
func (s *SRT) mergeStack(other *SRT) { func (s *SRT) mergeStack(other *SRT) {
size := s.Content.Size() + other.Content.Size() ls, _ := s.Content.(*glist.LinkedList[*SRTContent])
temp := make([]*SRTContent, size, size) lo, _ := other.Content.(*glist.LinkedList[*SRTContent])
index := 0 lhs, lho := ls.First, lo.First
for it := s.Content.Iterator(); it.Has(); { //临时的空结点
temp[index] = it.Next() preHead := &glist.Node[*SRTContent]{}
index++ prev := preHead
for lhs != nil && lho != nil {
//副本结点,从而不改变other对象中的内容
oCopy := lho.Clone()
if lhs.Element.Start <= oCopy.Element.Start {
prev.Next = lhs
lhs.Prev = prev
lhs = lhs.Next
} else {
prev.Next = oCopy
oCopy.Prev = prev
lho = lho.Next
} }
for it := other.Content.Iterator(); it.Has(); { prev = prev.Next
temp[index] = it.Next()
index++
} }
sort.SliceStable(temp, func(i, j int) bool { if lhs == nil {
return temp[i].Start < temp[j].Start //如果剩下的内容是other中的,则依次迭代复制到s中
}) for n := lho; n != nil; n = n.Next {
list := glist.NewLinkedList[*SRTContent]() c := n.Clone()
for _, v := range temp { prev.Next = c
list.Append(v) c.Prev = prev
prev = prev.Next
} }
s.Content = list } else {
prev.Next = lhs
}
ls.First = preHead.Next
ls.First.Prev = nil
} }
func (s *SRT) mergeUp(other *SRT) { func (s *SRT) mergeUp(other *SRT) {