• Leetcode_C++之238. Product of Array Except Self(除本身元素之外数组其他元素的积)


    题目名称

    1. Product of Array Except Self

    题目描述

    Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

    The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

    You must write an algorithm that runs in O(n) time and without using the division operation.

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

    Example 2:
    Input: nums = [-1,1,0,-3,3]
    Output: [0,0,9,0,0]

    Constraints:
    2 <= nums.length <= 105
    -30 <= nums[i] <= 30
    The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

    Follow up:
    Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

    初试思路

    1、空间换时间,用数组代替一层for循环。
    2、重复利用数组空间,避免额外数组,见注释。

    初试代码

    // 我的代码1
    class Solution {
    public:
        vector productExceptSelf(vector& nums) {
            // res[i] = num[0]*...*nums[i-1]*  1  *nums[i+1]*.. *nums[nums.size()-1]
            vector rights(nums.size());
            vector results(nums.size());
            rights[nums.size()-1] = 1;
            for(int i=nums.size()-1; i>0; i--){
                rights[i-1] = rights[i] * nums[i];
            }
            int left = 1;
            for(int i=0; i productExceptSelf(vector& nums) {
            // res[i] = num[0]*...*nums[i-1]*  1  *nums[i+1]*.. *nums[nums.size()-1]
            //vector rights(nums.size());
            vector results(nums.size());
            results[nums.size()-1] = 1; //重复利用results来存放rights
            for(int i=nums.size()-1; i>0; i--){
                results[i-1] = results[i] * nums[i];
            }
            int left = 1;
            for(int i=0; i
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    学到了啥

    1、问题拆解:左*右;
    2、空间换时间;
    3、若额外数组的元素都会只用到一次,则可以用省去该额外数组。

  • 相关阅读:
    开源库源码分析:OkHttp源码分析(二)
    Android充电驱动bq24375源码分析
    人工智能作业第二三章
    在java中类的继承原则有哪些?
    徐州存储服务器会应用在哪些场景?
    STM32学习笔记:USART
    【Java牛客刷题】入门篇(03)
    论坛议程|COSCon'23开源商业(V)
    JavaScript——JS事件
    【Microsoft Edge】如何彻底卸载 Edge
  • 原文地址:https://blog.csdn.net/m0_37864814/article/details/128117052