I am trying to convert this java code to swift in an attempt to answer this leetcode. Loading...
The output shows index out of bound; how do I resolve this ?
func productExceptSelf(_ nums: [Int]) -> [Int] {
var lArray = Array(repeating: 1, count: nums.count)
var rArray = Array(repeating: 1, count: nums.count)
var ansArray = [Int]()
for i in 1..<lArray.count{
lArray[i] = lArray[i-1] * nums[i-1]
}
for i in 1..<rArray.reversed().count{
rArray[i] = rArray[i+1] * nums[i+1]
}
for i in 0..<ansArray.count {
ansArray[i] = lArray[i] * rArray[i]
}
return ansArray
}
productExceptSelf([1,2,3,4])
var ansArray = [Int]()
for i in 1..<lArray.count{
lArray[i] = lArray[i-1] * nums[i-1]
}
for i in (0...(nums.count - 2)).reversed() {
rArray[i] = rArray[i+1] * nums[i+1]
}
for i in 0..<ansArray.count {
ansArray.append(lArray[i] * rArray[i])
print(ansArray)
}
return ansArray
Left array first item (larray[0]) is initialized with 1, right array last item (rarray[n - 1]) is initialized with 1 then left array is filled from second item to last item 1..<n and right array is filed from last but one to first item (0...(n - 2)).reversed(). And each step in loops use the result of the previous one.