亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中反轉數組?

如何在 Go 中反轉數組?

Go
墨色風雨 2021-06-30 10:07:46
http://play.golang.org/p/W70J4GU7nA  s := []int{5, 2, 6, 3, 1, 4}  sort.Reverse(sort.IntSlice(s))  fmt.Println(s)  // 5, 2, 6, 3, 1, 4很難理解它在 func Reverse(data Interface) Interface 中的含義。如何反轉數組?我不需要排序。
查看完整描述

3 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

通常情況下,要按整數數組你包起來的IntSlice,它定義了方法Len,Less和Swap。這些方法依次由sort.Sort. 是什么sort.Reverse做的是,它采用現有的類型定義Len,Less以及Swap,但它取代了Less用一個新的,始終是潛在的逆方法Less:


type reverse struct {

    // This embedded Interface permits Reverse to use the methods of

    // another Interface implementation.

    Interface

}


// Less returns the opposite of the embedded implementation's Less method.

func (r reverse) Less(i, j int) bool {

    return r.Interface.Less(j, i)

}


// Reverse returns the reverse order for data.

func Reverse(data Interface) Interface {

    return &reverse{data}

}

所以當你寫的時候sort.Reverse(sort.IntSlice(s)),發生的事情是你得到了這個新的、“修改過的” IntSlice,它的Less方法被替換了。因此,如果您調用sort.Sort它,即調用Less,它將按降序排序。


查看完整回答
反對 回復 2021-07-05
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

我遲到了 2 年,但只是為了好玩和感興趣,我想貢獻一個“奇怪的”解決方案。


假設任務確實是反轉列表,那么對于原始性能bgp的解決方案可能是無與倫比的。它通過前后交換數組項來簡單有效地完成工作,這種操作在數組和切片的隨機訪問結構中非常有效。


在函數式編程語言中,慣用的方法通常涉及遞歸。這在 Go 中看起來有點奇怪,而且性能會很差。也就是說,這是一個遞歸數組反轉函數(在一個小測試程序中):


package main


import (

    "fmt"

)


func main() {

    myInts := []int{ 8, 6, 7, 5, 3, 0, 9 }

    fmt.Printf("Ints %v reversed: %v\n", myInts, reverseInts(myInts))

}


func reverseInts(input []int) []int {

    if len(input) == 0 {

        return input

    }

    return append(reverseInts(input[1:]), input[0]) 

}

輸出:


Ints [8 6 7 5 3 0 9] reversed: [9 0 3 5 7 6 8]

同樣,這是為了好玩而不是生產。它不僅速度慢,而且如果列表太大,它還會溢出堆棧。我剛剛測試過,它會反轉 100 萬個ints的列表,但在 1000 萬個時崩潰。


查看完整回答
反對 回復 2021-07-05
  • 3 回答
  • 0 關注
  • 976 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號