arrays - Swift fatal error: Index out of range -


leetcode easy 88 merge sorted array

question:

given 2 sorted integer arrays nums1 , nums2, merge nums2 nums1 1 sorted array.

note:

you may assume nums1 has enough space (size greater or equal m + n) hold additionalelements nums2. number of elements initialized in nums1 , nums2 m , n respectively.

i got error have commented in code. have printed index2 , index3, both zero.they should legal. why got error?

any help, appreciate it. thank time!

class solution {     func merge(inout nums1:[int], _ m: int, _ nums2:[int], _ n: int)     {         var index1 = m - 1         var index2 = n - 1         var index3 = m + n - 1          while index2 >= 0 && index1 >= 0         {             if nums1[index1] > nums2[index2]             {                  nums1[index3] = nums1[index1]                 index3 -= 1                 index1 -= 1               }             else             {                 nums1[index3] = nums2[index2]                 index3 -= 1                 index2 -= 1             }         }          while index2 >= 0         {             print(index2)             print(index3)             nums1[index3] = nums2[index2] // fatal error: index out of range             index3 -= 1             index2 -= 1         }      } }    let test1 = solution() var haha = [int]() haha = [] test1.merge(&haha,0, [1],1) print(haha) 

your variable nums1 0-element array. there isn't space make assignment. is, index3=0 , you're using point first element of nums1, there not first element.

if, example, change:

haha = [] 

to:

haha = [0] 

then array nums1 have 0-th element inside method.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -