'I cannot allocate value in slide by using for loop in Go
Hello I am trying to study array in Leetcode.
I know that slide value will be reflected on original array by using array[index] = value.
But this code didn't work what I thought originally.
I cannot use pointer and return because I can only hand function in Leetcode.
Would you kindly check below my code?
I used Quick sort with partition.
Thank you.
https://go.dev/play/p/dNgYqPZCZqK
package main
import "fmt"
func main() {
nums1 := []int{1, 2, 3, 0, 0, 0}
nums2 := []int{2, 5, 6}
merge(nums1, len(nums1), nums2, len(nums2))
fmt.Println(nums1) // Expected : [1 2 2 3 5 6] but [1 2 3 0 0 0]
}
func merge(nums1 []int, m int, nums2 []int, n int) {
count := 0
nums1 = append(nums1, nums2...)
nums1 = quicksort(nums1, 0, m+n-1)
for i := range nums1 {
if nums1[i] == 0 {
count++
}
}
nums1 = nums1[count:]
for j := range nums1 {
nums1[j] = nums1[j] //self assignment for sure
}
fmt.Println(nums1) // [1 2 2 3 5 6]
}
func quicksort(arr []int, low, high int) []int {
if low < high {
arr, p := partition(arr, low, high)
arr = quicksort(arr, low, p-1)
arr = quicksort(arr, p+1, high)
}
return arr
}
func partition(arr []int, low, high int) ([]int, int) {
pivot := arr[high]
i := low
for j := low; j < high; j++ {
if arr[j] < pivot {
arr[i], arr[j] = arr[j], arr[i]
i++
}
}
arr[i], arr[high] = arr[high], arr[i]
return arr, i
}
Solution 1:[1]
I changed append variable from nums1 to temp. Maybe that made nums1 as copy slide.
So after changing nums1 to temp, later allocate values from temp to nums1.
It works!
https://go.dev/play/p/fU-06ZBWiFA
package main
import "fmt"
func main() {
nums1 := []int{1, 2, 3, 0, 0, 0}
nums2 := []int{2, 5, 6}
merge(nums1, len(nums1), nums2, len(nums2))
fmt.Println(nums1) // Expected : [1 2 2 3 5 6] but [1 2 3 0 0 0]
}
func merge(nums1 []int, m int, nums2 []int, n int) {
count := 0
temp := append(nums1, nums2...)
temp = quicksort(temp, 0, m+n-1)
for i := range temp {
if temp[i] == 0 {
count++
}
}
temp = temp[count:]
for j := range nums1 {
nums1[j] = temp[j] //self assignment for sure
}
fmt.Println(nums1)
}
func quicksort(arr []int, low, high int) []int {
if low < high {
arr, p := partition(arr, low, high)
arr = quicksort(arr, low, p-1)
arr = quicksort(arr, p+1, high)
}
return arr
}
func partition(arr []int, low, high int) ([]int, int) {
pivot := arr[high]
i := low
for j := low; j < high; j++ {
if arr[j] < pivot {
arr[i], arr[j] = arr[j], arr[i]
i++
}
}
arr[i], arr[high] = arr[high], arr[i]
return arr, i
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gopythor |
