• 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.)

    解题思路:

    套头多要求无法使用除法,还要在O(n)中完成。

    可以将每一个从前到后和从后到前的乘数保存下来,例如ret[8]就是0-6的相乘和8-n-1的相乘的相乘。

    这里还要是否考虑乘数可能溢出,是否要使用大数的问题,这里先用int试试

    1. class Solution {  
    2. public:  
    3.     vector<int> productExceptSelf(vector<int>& nums) {  
    4.   
    5.         int n = nums.size();  
    6.         vector<int> ret(n,1);  
    7.           
    8.         int from_start=1;  
    9.         int from_end=1;  
    10.           
    11.         for(int i=0;i<n;i++){  
    12.             ret[i]*=from_start;  
    13.             from_start*=nums[i];  
    14.             ret[n-i-1]*=from_end;  
    15.             from_end*=nums[n-i-1];     
    16.         }  
    17.         return ret;  
    18.           
    19.     }  
    20. };  
  • 相关阅读:
    第一次博客作业
    个人总结
    第三次个人作业——用例图设计
    第二次个人编程
    第一次个人编程
    第一次随笔
    个人总结
    第三次个人作业——用例图设计
    第二次结对作业
    第一次结对作业
  • 原文地址:https://www.cnblogs.com/liangyc/p/8794434.html
Copyright © 2020-2023  润新知