返回介绍

solution / 0200-0299 / 0238.Product of Array Except Self / README_EN

发布于 2024-06-17 01:04:02 字数 6335 浏览 0 评论 0 收藏 0

238. Product of Array Except Self

中文文档

Description

Given an integer array nums, return _an array_ answer _such that_ answer[i] _is equal to the product of all the elements of_ nums _except_ nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

 

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

 

Constraints:

  • 2 <= nums.length <= 105
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

 

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Solutions

Solution 1: Two Passes

We define two variables $left$ and $right$, which represent the product of all elements to the left and right of the current element respectively. Initially, $left=1$, $right=1$. Define an answer array $ans$ of length $n$.

We first traverse the array from left to right, for the $i$th element we update $ans[i]$ with $left$, then $left$ multiplied by $nums[i]$.

Then, we traverse the array from right to left, for the $i$th element, we update $ans[i]$ to $ans[i] \times right$, then $right$ multiplied by $nums[i]$.

After the traversal, the array ans is the answer.

The time complexity is $O(n)$, where $n$ is the length of the array nums. Ignore the space consumption of the answer array, the space complexity is $O(1)$.

class Solution:
  def productExceptSelf(self, nums: List[int]) -> List[int]:
    n = len(nums)
    ans = [0] * n
    left = right = 1
    for i, x in enumerate(nums):
      ans[i] = left
      left *= x
    for i in range(n - 1, -1, -1):
      ans[i] *= right
      right *= nums[i]
    return ans
class Solution {
  public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] ans = new int[n];
    for (int i = 0, left = 1; i < n; ++i) {
      ans[i] = left;
      left *= nums[i];
    }
    for (int i = n - 1, right = 1; i >= 0; --i) {
      ans[i] *= right;
      right *= nums[i];
    }
    return ans;
  }
}
class Solution {
public:
  vector<int> productExceptSelf(vector<int>& nums) {
    int n = nums.size();
    vector<int> ans(n);
    for (int i = 0, left = 1; i < n; ++i) {
      ans[i] = left;
      left *= nums[i];
    }
    for (int i = n - 1, right = 1; ~i; --i) {
      ans[i] *= right;
      right *= nums[i];
    }
    return ans;
  }
};
func productExceptSelf(nums []int) []int {
  n := len(nums)
  ans := make([]int, n)
  left, right := 1, 1
  for i, x := range nums {
    ans[i] = left
    left *= x
  }
  for i := n - 1; i >= 0; i-- {
    ans[i] *= right
    right *= nums[i]
  }
  return ans
}
function productExceptSelf(nums: number[]): number[] {
  const n = nums.length;
  const ans: number[] = new Array(n);
  for (let i = 0, left = 1; i < n; ++i) {
    ans[i] = left;
    left *= nums[i];
  }
  for (let i = n - 1, right = 1; i >= 0; --i) {
    ans[i] *= right;
    right *= nums[i];
  }
  return ans;
}
impl Solution {
  pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
    let n = nums.len();
    let mut ans = vec![1; n];
    for i in 1..n {
      ans[i] = ans[i - 1] * nums[i - 1];
    }
    let mut r = 1;
    for i in (0..n).rev() {
      ans[i] *= r;
      r *= nums[i];
    }
    ans
  }
}
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function (nums) {
  const n = nums.length;
  const ans = new Array(n);
  for (let i = 0, left = 1; i < n; ++i) {
    ans[i] = left;
    left *= nums[i];
  }
  for (let i = n - 1, right = 1; i >= 0; --i) {
    ans[i] *= right;
    right *= nums[i];
  }
  return ans;
};
public class Solution {
  public int[] ProductExceptSelf(int[] nums) {
    int n = nums.Length;
    int[] ans = new int[n];
    for (int i = 0, left = 1; i < n; ++i) {
      ans[i] = left;
      left *= nums[i];
    }
    for (int i = n - 1, right = 1; i >= 0; --i) {
      ans[i] *= right;
      right *= nums[i];
    }
    return ans;
  }
}
class Solution {
  /**
   * @param Integer[] $nums
   * @return Integer[]
   */
  function productExceptSelf($nums) {
    $n = count($nums);
    $ans = [];
    for ($i = 0, $left = 1; $i < $n; ++$i) {
      $ans[$i] = $left;
      $left *= $nums[$i];
    }
    for ($i = $n - 1, $right = 1; $i >= 0; --$i) {
      $ans[$i] *= $right;
      $right *= $nums[$i];
    }
    return $ans;
  }
}

Solution 2

function productExceptSelf(nums: number[]): number[] {
  return nums.map((_, i) => nums.reduce((pre, val, j) => pre * (i === j ? 1 : val), 1));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文