Leetcode 238: Product of Array doesn't Self, leetcodedoesn t

Source: Internet
Author: User

Leetcode 238: Product of Array doesn't Self, leetcodedoesn t
Product of Array partition t SelfTotal Accepted:938Total Submissions:2400

Given an arrayNIntegers whereN> 1,nums, Return an arrayoutputSuch thatoutput[i]Is equal to the product of all the elementsnumsExceptnums[i].

Solve itWithout divisionAnd in O (N).

For example, given[1,2,3,4], Return[24,12,8,6].

Follow up:
Cocould you solve it with constant space complexity? (Note: The output arrayDoes notCount as extra space for the purpose of space complexity analysis .)

[Idea]

Maintain two arrays, left [] and right []. record the sum of left [I] and right [I] on the left of element I, respectively. the result res [I] is left [I] + right [I]. follow up requires O (1) space. use the returned result array to store the right array first. calculate left from the left and the result value at the same time, so that no additional space is required.

[CODE]

public class Solution {    public int[] productExceptSelf(int[] nums) {        int[] res = new int[nums.length];        res[res.length-1] = 1;        for(int i=nums.length-2; i>=0; i--) {            res[i] = res[i+1] * nums[i+1];        }                int left = 1;        for(int i=0; i<nums.length; i++) {            res[i] *= left;            left *= nums[i];        }        return res;    }}


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.