gpt4 book ai didi

swift - 我的 Swift 代码出现错误无法形成上限 < 下限的范围

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:11 25 4
gpt4 key购买 nike

我尝试在 leetcode site 中运行我的代码.在 XCode 中,这段代码编译成功。但是在 leetcode 中是错误的:

Fatal error: Can't form range with upperbound < lowerbound

任务描述:

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

我对这个任务的解决方案是:

class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var arr: [[Int]] = []

var fIndex = 0
var sIndex = 1
var tIndex = 2

for i in fIndex..<nums.count-2 {
for n in sIndex..<nums.count-1 {
for z in tIndex..<nums.count {
let sum = nums[i] + nums[n] + nums[z]

if sum == 0 {
arr.append([nums[i], nums[n], nums[z]])
}
}

sIndex += 1
tIndex += 1
}

fIndex += 1
}

return arr
}
}
// delete this in leetcode site
let threeNums = [-1, 0, 1, 2, -1, -4]
let sol = Solution()
print(sol.threeSum(threeNums))

我的代码哪里出了问题?

最佳答案

假设代码的所有其他部分都有效,您只需要在循环之前检查输入数组的元素是否少于 3 个:

class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var arr: [[Int]] = []

var fIndex = 0
var sIndex = 1
var tIndex = 2

if nums.count < 3 { return [] } // if there is less than 3 elements, there can't be any triplets

for i in fIndex..<nums.count-2 {
...

如果没有检查,当 nums 只有一个元素时,您的代码将失败,而 enums.count - 2 将是 -1.

关于swift - 我的 Swift 代码出现错误无法形成上限 < 下限的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55469863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com