为了账号安全,请及时绑定邮箱和手机立即绑定

Golang升序

Golang升序

Go
湖上湖 2023-06-05 19:42:05
我在这里有一个 Go 语言问题,与下面我的相比,有没有更好的方法来回答编码 Golang 的答案?Mangkuk 是由最大尺寸的 Sudu 组成的列表。Sudu 是连续整数的排列,可能包含重复项。Cawan 是 Mangkuk,其中每个 Sudu 都按升序排序。编写一个函数 MakeCawan(→Mangkuk),将给定的 Mangkuk 排序为 Cawan。For example,MakeCawan([21, 20, 18, 20, 18, 20, 19]),MakeCawan([21, 2000000, 18, 20, 18, 20, 19]),MakeCawan([21, 20, 18, 20, 18, 20, 1900000])should produce, respectively,[18, 18, 19, 20, 20, 20, 21],[21, 2000000, 18, 18, 19, 20, 20],[20, 21, 18, 20, 18, 20, 1900000].package main    import (        "fmt"        "sort"    )    func main() {        sl := []string{"MakeCawan"}        sort.Sort(sort.StringSlice(sl))        fmt.Println(sl)                sl1 := []string{"MakeCawan"}        sort.Sort(sort.StringSlice(sl1))        fmt.Println(sl1)                sl2 := []string{"MakeCawan"}        sort.Sort(sort.StringSlice(sl2))        fmt.Println(sl2)                intSlice := []int{21,20,18,20,18,20,19}        sort.Sort(sort.IntSlice(intSlice))        fmt.Println(intSlice)    }输出:https://play.golang.org/p/tsE0BtMRos_9
查看完整描述

2 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

这个问题有点棘手:它不要求您对整个切片(或 mangkuk 在它自己的术语中)进行排序;它要求您首先识别称为 sudu 的所有连续间隔(可能有重复元素),然后对每个 sudu 进行排序。


func makeCawan(mangkuk []int) []int {

    for now, n := 0, len(mangkuk); now < n; {

        min := mangkuk[now]

        max := min

        head := now

    loop:

        for now++; now < n; now++ {

            switch x := mangkuk[now]; {

            case x < min-1 || x > max+1:

                sort(mangkuk[head:now], min, max)

                break loop

            case x == min-1:

                min = x

            case x == max+1:

                max = x

            }

        }

        if now >= n {

            sort(mangkuk[head:now], min, max)

        }

    }


    return mangkuk

}

游乐场:https://play.golang.org/p/z3TGWnWnrVY


查看完整回答
反对 回复 2023-06-05
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

回答这个问题假设你想对连续和重复的 int 切片进行排序。

简单地对切片进行排序是一种可读的解决方案,但是对于长度为 n 的切片使用基于比较的排序算法需要 O(nlgn)。

我们可以使用具有 O(n) 辅助空间的性能更好的算法。算法:
1. 迭代数组 A 并找到最小值和最大值。
2. 创建一个长度为 max-min+1 的数组 B。
3. 遍历 A 并将每个元素的计数存储在 B 中,即B[A[i] - min]++
4. 现在遍历 B 并打印 i + minB[i] 次。

时间复杂度 - O(n)

https://play.golang.org/p/rptgMpWdKCX

请注意,此循环也是 O(n),其中 n 是实际输入数组的长度。

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

        for b[i] != 0{

            fmt.Printf("%v ", i + min)

            b[i]--

        }

    }


查看完整回答
反对 回复 2023-06-05
  • 2 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信