当前位置:   article > 正文

LeetCode238Product of Array Except Self_238. product of array except self python

238. product of array except self python

先上题目:

这里写图片描述

题目大意:

给一数组。返回一数组,这个数组对应原数组除了对应数其他数的乘积和。注意为额外的O(n)空间

技巧:

题目中已经明确把最容易想到的求所有数乘积,然后分别除每一个数的简单做法给否定了,因为这个也太没技术含量了。。。

这里要提及一个经常用到的概念,前缀和后缀,这个概念对很多程序有至关重要的意义以后如果要介绍KMP算法,其中就用到了字符串前缀和后缀的匹配。其实前缀和后缀顾名思义我们可以把数组中特定一位元素,如i位元素,规定i之前的元素乘积和为i的前缀积,同理i之后的元素乘积和为i的后缀积,显然输出的数组为前缀积数组再乘上后缀积数组对应的元素。

如下图所示

这里写图片描述
这里写图片描述

示例代码:

在实例代码中,我只用了两个vector数组,一个是结果的,一个是原有的,这破坏了原有的nums中的值,如果题目没有要保持原有数组的要求的话,这种实现又节省了一定的额外空间。
#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> prefix;
        int size = nums.size();


        prefix.push_back(1);    // 初值赋为1很关键
        for (int i = 1; i < size; i++) {
            int temp = prefix[i-1]*nums[i-1];
            prefix.push_back(temp);

        }


        int templast = nums[size-1];   // 这里要记录即将被修改的nums数组值
        nums[size-1]=1;
        for (int i = 1; i < size; i++) {
            int temp = nums[size-i]*templast;  
            templast = nums[size-i-1];  // 更新templast的值
            nums[size-i-1] = temp;
        }

        for (int i = 0; i < size; i++) {
            prefix[i] *= nums[i];
        }

        return prefix;
    }
};

int main() {
    Solution s;
    vector<int> temp;
    int n;
    cin >> n;
    cout << endl << endl;

    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        temp.push_back(x);
    }
    vector<int> printarray = s.productExceptSelf(temp);

    for (int i = 0; i < printarray.size(); i++) {
        cout << printarray[i] << " ";
    }
    cout << endl;
    getchar();
    getchar();
    return 0;

}
  • 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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

运行截图:

这里写图片描述

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/818405
推荐阅读
相关标签
  

闽ICP备14008679号