Leetcode_C++之238. Product of Array Except Self(除本身元素之外数组其他元素的积)
admin
2024-03-04 11:31:56

题目名称

  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来存放rightsfor(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、若额外数组的元素都会只用到一次,则可以用省去该额外数组。

相关内容

热门资讯

广百股份涨0.88%,成交额1... 1月20日,广百股份涨0.88%,成交额11.69亿元,换手率18.19%,总市值64.06亿元。异...
中天服务涨2.13%,成交额1... 1月20日,中天服务涨2.13%,成交额1.62亿元,换手率9.48%,总市值21.98亿元。异动分...
榕基软件跌4.57%,成交额4... 1月20日,榕基软件跌4.57%,成交额4.64亿元,换手率8.95%,总市值59.79亿元。异动分...
汉森制药涨0.88%,成交额4... 1月20日,汉森制药涨0.88%,成交额4375.73万元,换手率1.28%,总市值34.57亿元。...
生意宝跌0.37%,成交额1.... 1月20日,生意宝跌0.37%,成交额1.39亿元,换手率2.91%,总市值47.92亿元。异动分析...