https://leetcode-cn.com/problems/product-of-array-except-self/ 数组

暴力破解

  1. function productExceptSelf(nums: number[]): number[] {
  2. function getLeft(k) {
  3. let left = 1
  4. for (let i = 0; i < k; i++) {
  5. left = left * nums[i]
  6. }
  7. return left
  8. }
  9. function getRight(k) {
  10. let right = 1
  11. for (let i = k + 1; i < nums.length; i++) {
  12. right = right * nums[i]
  13. }
  14. return right
  15. }
  16. const res = []
  17. nums.map((item, index) => {
  18. res.push(getLeft(index) * getRight(index))
  19. })
  20. return res
  21. };

正反遍历

image.png
image.png

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
};