例如,我修复了 rotate 算法中的错误后, 程序包主要导入"fmt"func rotation(nums [] int,k int)[] int {如果k <0 ||len(nums)== 0 {返回数字}fmt.Printf(数字%p数组%p len%d上限%d切片%v \ n",& nums,& nums [0],len(nums),cap(nums),nums)r:= len(数字)-k%len(数字)nums = append(nums [r:],nums [:r] ...)fmt.Printf(数字%p数组%p len%d上限%d切片%v \ n",& nums,& nums [0],len(nums),cap(nums),nums)返回数字}func main(){nums:= [] int {1、2、3、4、5、6、7}fmt.Printf(数字%p数组%p len%d上限%d切片%v \ n",& nums,& nums [0],len(nums),cap(nums),nums)nums =旋转(nums,3)fmt.Printf(数字%p数组%p len%d上限%d切片%v \ n",& nums,& nums [0],len(nums),cap(nums),nums)} 输出: 数字0xc00000a080数组0xc00001a1c0 len 7 cap 7 slice [1 2 3 4 5 6 7]nums 0xc00000a0c0数组0xc00001a1c0 len 7 cap 7 slice [1 2 3 4 5 6 7]nums 0xc00000a0c0数组0xc00001a240 len 7 cap 8 slice [5 6 7 1 2 3 4]nums 0xc00000a080数组0xc00001a240 len 7 cap 8 slice [5 6 7 1 2 3 4] 参考: The Go博客:Go Slices:用法和内部原理 This is a LeetCode problem: 189. Rotate Array:And here is my solution:func rotate(nums []int, k int) { k = k % len(nums) nums = append(nums[k:],nums[0:k]...) fmt.Println(nums)}It is a straight forward algorithm but it does not work.I am new to Go. I suppose nums is passed by value and changes to nums won't affect the real nums. How can I get this right? 解决方案 In Go, all arguments are passed by value.A Go slice is represented at runtime by a slice descriptor:type slice struct { array unsafe.Pointer len int cap int}If you change any of the slice descriptor values in a function then communicate the change, typically by returning the changed slice descriptor.Your rotate function changes the values of the slice num pointer to the underlying array and the slice capacity, so return num.For example, after I fixed the bugs in your rotate algorithm,package mainimport "fmt"func rotate(nums []int, k int) []int { if k < 0 || len(nums) == 0 { return nums } fmt.Printf("nums %p array %p len %d cap %d slice %v\n", &nums, &nums[0], len(nums), cap(nums), nums) r := len(nums) - k%len(nums) nums = append(nums[r:], nums[:r]...) fmt.Printf("nums %p array %p len %d cap %d slice %v\n", &nums, &nums[0], len(nums), cap(nums), nums) return nums}func main() { nums := []int{1, 2, 3, 4, 5, 6, 7} fmt.Printf("nums %p array %p len %d cap %d slice %v\n", &nums, &nums[0], len(nums), cap(nums), nums) nums = rotate(nums, 3) fmt.Printf("nums %p array %p len %d cap %d slice %v\n", &nums, &nums[0], len(nums), cap(nums), nums)}Output:nums 0xc00000a080 array 0xc00001a1c0 len 7 cap 7 slice [1 2 3 4 5 6 7]nums 0xc00000a0c0 array 0xc00001a1c0 len 7 cap 7 slice [1 2 3 4 5 6 7]nums 0xc00000a0c0 array 0xc00001a240 len 7 cap 8 slice [5 6 7 1 2 3 4]nums 0xc00000a080 array 0xc00001a240 len 7 cap 8 slice [5 6 7 1 2 3 4]Reference: The Go Blog: Go Slices: usage and internals 这篇关于Go中的旋转阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 19:17