zoukankan      html  css  js  c++  java
  • LN : leetcode 238 Product of Array Except Self

    lc 238 Product of Array Except Self


    238 Product of Array Except Self

    Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Solve it without division and in O(n).

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

    Follow up:

    Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

    Accepted

    本来可以先求出所有元素的积,再以O(n)的复杂度遍历除得答案,但题目要求不能使用除法。

    我们知道对于答案的第一位一定等于从后往前乘,直至乘到它为止,不包括它自身;而答案的最后一位一定等于从前往后乘,直至乘到它为止,不包括它自身。所以我们定义两个变量,frombegin代表从前往后的积,fromlast代表从后往前的积。

    通过一层for循环,对于每一次迭代都对当前元素乘上frombegin,对其对称位乘上fromlast,这样最终就可以很神奇地得到除去自身外的其他位的乘积。

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size(), frombegin = 1, fromlast = 1;
            vector<int> ans(n,1);
            for (int i = 0; i < n; i++) {
                ans[i] *= frombegin;
                frombegin *= nums[i];
                ans[n-1-i] *= fromlast;
                fromlast *= nums[n-1-i];
            }
            return ans;
        }
    };
    
  • 相关阅读:
    SharePoint 2010 Managed Metadata Columns and Metadata Navigation Settings
    SharePoint 知识整理1
    印度HCL揭秘云计算五大盈利模式
    云计算盈利模式都有什么?
    IaaS
    Salesforce
    走近云计算:解密IaaS PaaS SaaS的关系
    sasdas
    解析salesforce
    Salesforce成功的秘密
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7711299.html
Copyright © 2011-2022 走看看