3 回答

TA貢獻1802條經驗 獲得超5個贊
嘗試這個:
func allLongestStrings(inputArray []string) []string {
? ? max := -1 // -1 is guaranteed to be less than length of string
? ? var result []string
? ? for _, s := range inputArray {
? ? ? ? if len(s) < max {
? ? ? ? ? ? // Skip shorter string
? ? ? ? ? ? continue
? ? ? ? }
? ? ? ? if len(s) > max {
? ? ? ? ? ? // Found longer string. Update max and reset result.
? ? ? ? ? ? max = len(s)
? ? ? ? ? ? result = result[:0]
? ? ? ? }
? ? ? ? // Add to result
? ? ? ? result = append(result, s)
? ? }
? ? return result
}
結果切片的容量可以大于所需的容量,并且可以包含超過切片長度的字符串值。額外的分配和字符串引用在某些情況下可能是個問題(結果保留很長時間,字符串很大,...)。如果分配和引用是一個問題,則返回切片的副本。
func allLongestStrings(inputArray []string) []string {
? ? ...
? ? return append([]string(nil), result...)
}
如果函數可以改變原始切片,則可以在輸入切片中構造函數結果。這避免了結果切片的分配。
func allLongestStrings(inputArray []string) []string {
? ? n := 0
? ? max := -1
? ? for i, s := range inputArray {
? ? ? ? if len(s) < max {
? ? ? ? ? ? // Skip shorter string
? ? ? ? ? ? continue
? ? ? ? }
? ? ? ? if len(s) > max {
? ? ? ? ? ? // Found longer string. Update max and reset result.
? ? ? ? ? ? max = len(s)
? ? ? ? ? ? n = 0
? ? ? ? }
? ? ? ? inputArray[n], inputArray[i] = inputArray[i], inputArray[n]
? ? ? ? n++
? ? }
? ? return inputArray[:n]
}

TA貢獻1909條經驗 獲得超7個贊
我會通過使用 sort 包來做到這一點?;旧希龅氖峭ㄟ^實現sort.Interface并使用sort.Sort來創建自定義排序功能。
package main
import "sort"
import "fmt"
type sortByLength []string
// Len implements Len of sort.Interface
func (s sortByLength) Len() int {
? ?return len(s)
}
// Swap implements Swap of sort.Interface
func (s sortByLength) Swap(i, j int) {
? ?s[i], s[j] = s[j], s[i]
}
// Less implements Less of sort.Interface
func (s sortByLength) Less(i, j int) bool {
? ? return len(s[i]) > len(s[j])
}
func main() {
? ? toFind := []string{"aa", "aab", "bcd", "a", "cdf", "bb"}
? ? // We sort it by length, descending
? ? sort.Sort(sortByLength(toFind))
? ? // The first element is sure to be the longest
? ? longest := []string{toFind[0]}
? ? // In case we have more than one element in toFind...
? ? if len(toFind) > 1 {
? ? ? ? // ...we need to find all remaining elements of toFind...
? ? ? ? for _, str := range toFind[1:] {
? ? ? ? ? ? // ...which are not smaller than the first element of longest.
? ? ? ? ? ? if len(str) < len(longest[0]) {
? ? ? ? ? ? ? ? // In case the current element is smaller in length, we can stop iterating
? ? ? ? ? ? ? ? // over toFind.
? ? ? ? ? ? ? ? break
? ? ? ? ? ? }
? ? ? ? ? ? // We know that str has the same length as longest[0], so we append it
? ? ? ? ? ? longest = append(longest, str)
? ? ? ? }
? ? }
? ? fmt.Println(longest)
}
然而,雖然您自己的代碼中只有一個循環,但排序顯然也會遍歷輸入。

TA貢獻1834條經驗 獲得超8個贊
例如
package main
import "fmt"
func longest(a []string) []string {
? ? var l []string
? ? if len(a) > 0 {
? ? ? ? l = append(l, a[0])
? ? ? ? a = a[1:]
? ? }
? ? for _, s := range a {
? ? ? ? if len(l[0]) <= len(s) {
? ? ? ? ? ? if len(l[0]) < len(s) {
? ? ? ? ? ? ? ? l = l[:0]
? ? ? ? ? ? }
? ? ? ? ? ? l = append(l, s)
? ? ? ? }
? ? }
? ? return append([]string(nil), l...)
}
func main() {
? ? a := []string{"aa", "aab", "bcd", "a", "cdf", "bb"}
? ? fmt.Println(len(a), a)
? ? l := longest(a)
? ? fmt.Println(len(l), cap(l), l)
}
游樂場:https://play.golang.org/p/JTvl4wVvSEK
輸出:
6?[aa?aab?bcd?a?cdf?bb] 3?4?[aab?bcd?cdf]
例如,對于最大值和最小值問題,避免使用特殊值作為初始最大值或最小值。不要過度分配內存,也不要留下懸空指針。
Gostring
實現為:
type stringStruct struct {
? ? str unsafe.Pointer
? ? len int
}
如果列表由 1,000 個長度為 1,000 的字符串和一個長度為 1,001 的字符串組成,則返回的列表的長度為 1,容量至少為 1,000。999 個條目有指向 1,000 字節字符串的懸垂指針,Go gc 將無法釋放這些字符串,浪費超過 1 兆字節。
package main
import (
? ? "fmt"
? ? "strings"
? ? "unsafe"
)
type stringStruct struct {
? ? str unsafe.Pointer
? ? len int
}
func main() {
? ? var l []string
? ? for n := 0; n < 1000; n++ {
? ? ? ? l = append(l, strings.Repeat("x", 1000))
? ? }
? ? l = l[:0]
? ? l = append(l, strings.Repeat("y", 1001))
? ? over := (cap(l) - len(l)) * int(unsafe.Sizeof(stringStruct{}))
? ? for i, o := len(l), l[:cap(l)]; i < cap(l); i++ {
? ? ? ? over += len(o[i])
? ? }
? ? fmt.Println(over) // 1015368 bytes 64-bit, 1007184 bytes 32-bit?
}
游樂場:https://play.golang.org/p/Fi7EgbvdVkp
一個程序要正確,就必須是可讀的。首先,在不受錯誤或特殊情況干擾的情況下編寫基本算法。
var l []string
for _, s := range a {
? ? if len(l[0]) <= len(s) {
? ? ? ? if len(l[0]) < len(s) {
? ? ? ? ? ? l = l[:0]
? ? ? ? }
? ? ? ? l = append(l, s)
? ? }
}
接下來,在不中斷基本算法流程的情況下添加特殊情況。在這種情況下,處理零和一長度列表。
var l []string
if len(a) > 0 {
? ? l = append(l, a[0])
? ? a = a[1:]
}
for _, s := range a {
? ? if len(l[0]) <= len(s) {
? ? ? ? if len(l[0]) < len(s) {
? ? ? ? ? ? l = l[:0]
? ? ? ? }
? ? ? ? l = append(l, s)
? ? }
}
最后,確保函數對 CPU 和內存都有效。分配是精確的,沒有指向未使用字符串的懸垂指針。
var l []string
if len(a) > 0 {
? ? l = append(l, a[0])
? ? a = a[1:]
}
for _, s := range a {
? ? if len(l[0]) <= len(s) {
? ? ? ? if len(l[0]) < len(s) {
? ? ? ? ? ? l = l[:0]
? ? ? ? }
? ? ? ? l = append(l, s)
? ? }
}
return append([]string(nil), l...)
- 3 回答
- 0 關注
- 228 瀏覽
添加回答
舉報