Product of Array Except Self
来源:互联网 发布:stl源码剖析pdf百度云 编辑:程序博客网 时间:2024/05/24 05:18
题目描述:
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]
.
使用两个辅助数组left和right,left[i]表示数组nums的[0,i-1]区间元素的乘积,right[i]表示数组nums的[i+1,n-1]区间元素的乘积,那么output[i]=left[i]*right[i]
AC代码如下:
class Solution {public:vector<int> productExceptSelf(vector<int>& nums) {int n = nums.size();if (n <= 1) return vector<int>();vector<int> ans(n);vector<int> left(n,1);vector<int> right(n,1);for (int i = 1; i < n; ++i){left[i] = left[i - 1] * nums[i - 1];}for (int i = n - 2; i >= 0; --i){right[i] = right[i + 1] * nums[i + 1];}for (int i = 0; i < n; ++i){ans[i] = left[i] * right[i];}return ans;}};
上述方法使用的额外空间为O(n),下面的方法使用的额外空间为O(1)。
解题思路:
先用最后要返回的数组output来保存向右累计的乘积,即output[i]表示数组nums的[i+1,n-1]区间元素的乘积,然后再从头遍历一遍数组,使用一个变量product来保存数组nums的[0,i-1]区间元素的乘积,并更新output[i]=output[i]*product即可得到最后的结果
AC代码如下:
class Solution{public:vector<int> productExceptSelf(vector<int>& nums) {int n = nums.size();if (n <= 1) return vector<int>();vector<int> ans(n,1);for (int i = n - 2; i >= 0; --i){ans[i] = ans[i + 1] * nums[i + 1];}int product = 1;for (int i = 0; i < n; ++i){ans[i] = ans[i]*product;product *= nums[i];}return ans;}};
0 0
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- wxpython实现图灵机器人的GUI-Python
- filename.whl is not supported wheel on this platform
- 回忆多项式解析运算思路
- Bootstrap是什么,Bootstrap里的文件分别表示什么?都有什么用?
- JDBC的简介及操作
- Product of Array Except Self
- LVS+Keepalived负载均衡操作手册
- Android:android sdk源码中怎么没有httpclient的源码了
- LeetCode和牛客网的对比
- HDU 2089 不要62
- C语言中声明与定义的意义和使用方法
- JVM内存堆布局图解分析
- CodeForces 659 B. Qualifying Contest(结构体排序的问题)
- Unity Shader简单Shader二