zoukankan      html  css  js  c++  java
  • 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. };  
  • 相关阅读:
    Executors源码之线程池
    Java序列化对字段名的影响
    Spring Cloud Alibaba(二)
    Security版本冲突,老版本共用服务接入新版本服务
    记一次虚拟机崩溃事件和解决方法(CentOS7)
    vue-cli 项目构建学习笔记(Vue3)
    IDEA插件-IDE Eval Reset
    Docker的学习
    Spring Security的学习
    Spring MVC框架的设计理念
  • 原文地址:https://www.cnblogs.com/liangyc/p/8794434.html
Copyright © 2011-2022 走看看