Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

238. Product of Array Except Self #114

Open
Tcdian opened this issue Apr 15, 2020 · 1 comment
Open

238. Product of Array Except Self #114

Tcdian opened this issue Apr 15, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 15, 2020

238. Product of Array Except Self

给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

Example

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

Constraint

  • 题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。

Note

  • 请不要使用除法 ,且在 O(n) 时间复杂度内完成此题。

Follow up

  • 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 15, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function(nums) {
    const result = new Array(nums.length);
    let prefixLeft = 1;
    for (let i = 0; i < nums.length; i++) {
        result[i] = prefixLeft;
        prefixLeft *= nums[i];
    }
    let prefixRight = 1;
    for (let i = nums.length - 1; i >= 0; i--) {
        result[i] *= prefixRight;
        prefixRight *= nums[i];
    }
    return result;
};
  • TypeScript Solution
function productExceptSelf(nums: number[]): number[] {
    const result: number[] = new Array(nums.length);
    let prefixLeft = 1;
    for (let i = 0; i < nums.length; i++) {
        result[i] = prefixLeft;
        prefixLeft *= nums[i];
    }
    let prefixRight = 1;
    for (let i = nums.length - 1; i >= 0; i--) {
        result[i] *= prefixRight;
        prefixRight *= nums[i];
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant