如何按另一个字符串片给出的顺序对一个字符串片进行排序。如果输入片中没有该字符串,则忽略它。
animalsInput := []string{"cat", "bird", "zebra", "fox"}
animalsOrder := []string{"bird", "lion", "fox"}
//desired output
//{"bird", "fox", "cat", "zebra"}
答案 0 :(得分:3)
一种实现此目的的方法是通过基于订单数组编写rank
映射
rank:=map[string]int{}
for i, x:=range animalsOrder {
rank[x]=i
}
然后在rank
中使用sort
:
sort.Slice(animalsInput,func(i,j int) bool {
irank, ok:=rank[animalsInput[i]]
if !ok {
irank=len(animalsInput)
}
jrank, ok:=rank[animalsInput[j]]
if !ok {
jrank=len(animalsInput)
}
return irank<jrank
})
答案 1 :(得分:1)
您可以尝试以下代码:
package main
import (
"fmt"
)
func sort(in, order []string) (out []string) {
flag := make([]bool, len(in))
out = make([]string, len(in))
orderCountMap := make(map[string]int)
for i := range in {
orderCountMap[in[i]] += 1
}
for i := range in {
if _, found := orderCountMap[in[i]]; found {
flag[i] = true
} else {
flag[i] = false
}
}
p := 0
for i := range order {
if v, found := orderCountMap[order[i]]; found {
for j := 0; j < v; j++ {
out[p] = order[i]
p += 1
}
}
}
for i := range flag {
if !flag[i] {
out[p] = in[i]
p += 1
}
}
return
}
func main(){
animalsInput := []string{"cat", "bird", "zebra", "fox"}
animalsOrder := []string{"bird", "lion", "fox", "zebra", "cat"}
out := sort(animalsInput, animalsOrder)
fmt.Println(out)
}