LeetCode 238. Product of Array Except Self
来源:互联网 发布:广州聚焦网络怎么样 编辑:程序博客网 时间:2024/06/08 11:32
Description:
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.)
本题第一眼看时觉得挺简单的,以为只需要先将第一个位置的积求出来,再遍历一遍vector在每个元素位置将该位置的元素除去便可得到结果,这应该是常规会想到的解法,然而发现题意描述中给了一个限制条件:不能使用除法。
好吧,另辟蹊径,细读题目描述,可以发现该题要求输出的数组的一个特性:对于输出结果的每个元素,可以将其乘积分成两部分:该位置的乘积是其左边所有元素的乘积和右边所有元素的乘积的乘积。因此,我们就能将该问题分成两个子问题了:先求出每个位置的左部分乘积,再求出每个位置的右部分乘积,之后再次遍历将左部分和右部分做乘积,即可得到答案。
代码如下:
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> result; vector<int> temp;//用于存放每个元素右部分的乘积 //存放右部分的vector采取倒序放置,即首元素为nums的末元素的右部分乘积 result.push_back(1);//初始元素没有左部分,置为1 temp.push_back(1);//同理,末元素没有右部分,置为1 for(int i = 1; i < nums.size(); i++) { result.push_back(nums[i - 1] * result[i - 1]); temp.push_back(nums[nums.size() - i] * temp[i - 1]); } for(int i = 0; i < nums.size(); i++) { result[i] *= temp[nums.size() - i - 1]; } return result; }};
阅读全文
0 0
- [leetcode] 238.Product of Array Except Self
- [LeetCode]238.Product of Array Except Self
- [leetcode] 238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self LeetCode
- LeetCode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- LeetCode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- leetcode-238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- LeetCode- 238. Product of Array Except Self
- leetcode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- leetcode:238. Product of Array Except Self
- jdbc连接操作mysql,直接操作和预处理方式
- 书目
- Django模板无法使用perms变量问题解决办法详解
- HDU
- 周末记录--2017.9.10(最长上升子序列优化算法)
- LeetCode 238. Product of Array Except Self
- spring boot起步-搭建eureka环境
- 算法day02
- 对二叉树的复习与整理
- weblogic10数据源(连接池)配置
- linux中proc文件系统
- EditorTools分析
- 9月8日笔记(servlet相关知识)
- Apache Beam中的几种常见的处理类