Go語言中的多維陣列傳遞

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。在Go語言中,當多維陣列直接作為函數實參進行參數傳遞的時候,會有很大的限制性,比如除第一維數組的其他維數需要顯式給出等;此時可以使用多維切片來作為參數傳遞:

type s1 []int

type s2 []s1

劍指offer一書面試題3:

在一個二維數組中,每一行都按照從左至右遞增的順序排序,每一列按照從上到下的順序排序。完成一個函數,輸入二維數組和要尋找的數,判斷該數是否存在於二維數組中。
代碼:


package mainimport ("errors""fmt""os")type s1 []inttype s2 []s1var searchErr error = errors.New("search error")func main() {a := s2{s1{1, 2, 3, 4, 5, 6},s1{7, 8, 9, 10, 11, 12},s1{13, 14, 15, 16, 17, 18},s1{20, 21, 22, 23, 24, 25}}result, err := search(a[:][:], 4, 6, 21)if err != nil {fmt.Println(err)os.Exit(1)}if result == true {fmt.Println("Key is searched")}}func search(a s2, row, col, key int) (flag bool, err error) {if row < 0 || col < 0 {return false, searchErr}flag = falserowNum := 0colNum := col - 1for rowNum < row && colNum >= 0 {if a[rowNum][colNum] == key {flag = truebreak} else if a[rowNum][colNum] > key {colNum--} else {rowNum++}}return}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.