Go語言程式:查詢陣列中指定元素的首次出現索引
本文將編寫一個Go語言程式,用於查詢陣列中指定元素的首次出現索引。我們將使用for迴圈和內建的Go庫函式來實現此結果。
方法一:使用SearchInts()庫函式
語法
func Sort(data Interface)
sort()函式位於sort包中。此函式用於將陣列按升序排序。待排序的陣列作為引數傳遞給該函式。此函式的時間複雜度為O(n * logn)。
type IntSlice []int
IntSlice()函式位於sort包中。此函式用於將介面方法附加到int陣列,以便可以按升序對其進行排序。
func SearchInts(a []int, x int) int
SearchInts()函式位於sort包中。此函式用於在整數陣列中搜索特定元素。該函式接受陣列以及要搜尋的元素作為引數,並返回該特定元素的索引作為結果。
演算法
步驟1 − 首先,我們需要匯入fmt和sort包。
步驟2 − 然後,啟動main()函式。在main()中,使用make函式初始化一個整數陣列,並使用append()函式將元素儲存到陣列中。
步驟3 − 現在,在螢幕上列印陣列,並使用sort包中的IntSlice()和Sort()函式將陣列按升序排序。
步驟4 − 接下來,在螢幕上列印排序後的陣列,並將要搜尋的元素儲存在一個名為elem的變數中。
步驟5 − 現在,為了獲取上述所選元素的索引,使用sort包的SearchInts()函式,並將陣列以及elem變數作為引數傳遞給該函式。
步驟6 − 將函式返回的結果(即該元素首次出現的索引)儲存在一個變數中,並使用fmt.Println()函式在螢幕上列印它。
在這個例子中,我們將編寫一個Go語言程式,使用SearchInts()庫函式查詢整數陣列中元素的首次出現索引。
package main import ( "fmt" "sort" ) func main() { // initializing an array array := make([]int, 0, 5) array = append(array, 74, 59, -784, 784, 59) a := sort.IntSlice(array[0:]) sort.Sort(a) var elem int = 59 fmt.Println("The array is:", a) pos := sort.SearchInts(a, elem) fmt.Println("The position of", elem, "in the array is:", pos) }
輸出
The array is: [-784 59 59 74 784] The position of 59 in the array is: 1
方法二:使用SearchString()函式
語法
type StringSlice []string
StringSlice()函式位於sort包中。此函式用於將介面方法附加到字串陣列,以便可以按升序對其進行排序。
func SearchStrings(a []int, x int) int
SearchStrings()函式位於sort包中。此函式用於在字串陣列中搜索特定元素。該函式接受陣列以及要搜尋的元素作為引數,並返回該特定元素的索引作為結果。
演算法
步驟1 − 首先,我們需要匯入fmt和sort包。
步驟2 − 然後,啟動main()函式。在main()中,使用make函式初始化一個字串陣列,並使用append()函式將元素儲存到陣列中。
步驟3 − 現在,在螢幕上列印陣列,並使用sort包中的StringSlice()和Sort()函式將陣列按升序排序。
步驟4 − 接下來,在螢幕上列印排序後的陣列,並將要搜尋的元素儲存在一個名為elem的變數中。
步驟5 − 現在,為了獲取上述所選元素的索引,使用sort包的SearchString()函式,並將陣列以及elem變數作為引數傳遞給該函式。
步驟6 − 將函式返回的結果(即該元素首次出現的索引)儲存在一個變數中,並使用fmt.Println()函式在螢幕上列印它。
示例
在這個例子中,我們將編寫一個Go語言程式,使用SearchStrings()庫函式查詢整數陣列中元素的首次出現索引。(原文有誤,應為字串陣列)
package main import ( "fmt" "sort" ) func main() { // initializing an array array := make([]string, 0, 7) array = append(array, "d", "c", "b", "y", "x", "a", "x") a := sort.StringSlice(array[0:]) sort.Sort(a) var elem string = "x" fmt.Println("The array is:", a) pos := sort.SearchStrings(a, elem) fmt.Println("The position of", elem, "in the array is:", pos) }
輸出
The array is: [a b c d x x y] The position of x in the array is: 4
結論
我們已經成功編譯了一個Go語言程式,用於查詢陣列中指定元素的首次出現索引,並附帶示例。