https://leetcode-cn.com/problems/product-of-array-except-self/ 数组
暴力破解
function productExceptSelf(nums: number[]): number[] {
function getLeft(k) {
let left = 1
for (let i = 0; i < k; i++) {
left = left * nums[i]
}
return left
}
function getRight(k) {
let right = 1
for (let i = k + 1; i < nums.length; i++) {
right = right * nums[i]
}
return right
}
const res = []
nums.map((item, index) => {
res.push(getLeft(index) * getRight(index))
})
return res
};
正反遍历
function productExceptSelf(nums: number[]): number[] {
const res = []
for (let i = 0, temp = 1; i < nums.length; i++) {
res[i] = temp
temp *= nums[i]
}
for (let i = nums.length - 1, temp = 1; i >= 0; i--) {
res[i] *= temp
temp *= nums[i]
}
return res
};