【问题标题】:Swift fatal error: Index out of rangeSwift 致命错误:索引超出范围
【发布时间】:2016-08-15 11:08:24
【问题描述】:

LeetCode Easy 88 合并排序数组

问题:

给定两个排序整数数组 nums1 和 nums2,将 nums2 合并为 nums1 作为一个排序数组。

注意:

您可以假设 nums1 有足够的空间(大小大于或等于 m + n)来容纳来自 nums2 的其他元素。 nums1和nums2中初始化的元素个数分别为m和n。

我收到了一个错误,我已在我的代码中进行了注释。我已经打印了 index2 和 index3,它们都是零。它们应该是合法的。为什么会出现这个错误?

任何帮助,我很感激。非常感谢您的宝贵时间!

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)

【问题讨论】:

    标签: arrays swift2 fatal-error


    【解决方案1】:

    您的变量 nums1 是一个 0 元素数组。所以没有空间让你做任务。即index3=0,你用它来指向nums1的第一个元素,但是没有第一个元素。

    例如,如果您更改:

    haha = []
    

    到:

    haha = [0]
    

    那么您的数组 nums1 将在方法中包含第 0 个元素。

    【讨论】:

    • 非常感谢!这对我来说完全有道理。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多