<LeetCode OJ> 238. Product of Array Except Self
来源:互联网 发布:qq群营销软件 编辑:程序博客网 时间:2024/06/07 01:00
给定一个数组nums,且其长度大于1,返回一个数组output,此数组output[i]等于除掉nums[i]外所有元素的乘积
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).不要用除法,性能要求为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.)
1,最朴素的做法:
求output[i]时,用两层循环,将除掉nums[i]外所有元素的相乘。当然,是无法AC的(写着玩)。
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> result(nums.size(),1); for(int i=0;i<nums.size();i++) for(int j=0;j<nums.size();j++) if(j!=i) result[i]*=nums[j]; return result; }};
参考讨论区
2,技巧法:
百度了一下发现的普遍方法(尼玛大家尽然都想一块去了):
具体过程是:要计算output[i],
就先计算,leftResult[i] = nums[0]*nums[1]*...*nums[i-1],
再计算,rightResult[i] = nums[i+1]*nums[i+2]*...*nums[n-1]
然后将这两个值相乘即为leftResult[i]*rightResult[i]=output[i]。
time,o(n),space,o(n)
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> leftResult(nums.size(),1);//记录当前数nums[i]左边所有数的乘积,如果没有则是1 vector<int> rightResult(nums.size(),1); //记录当前数nums[i]右边所有数的乘积,如果没有则是1 for(int i=1;i<nums.size();i++) { leftResult[i]=leftResult[i-1]*nums[i-1]; rightResult[nums.size()-i-1]=rightResult[nums.size()-i]*nums[nums.size()-i]; } vector<int> result(nums.size()); for(int i=0;i<nums.size();i++) result[i]=leftResult[i]*rightResult[i]; return result; }};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50574787
原作者博客:http://blog.csdn.net/ebowtang
- <LeetCode OJ> 238. Product of Array Except Self
- LeetCode OJ 238. Product of Array Except Self 解题报告
- LeetCode oj 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
- 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
- USACO-Section 3.1-PROB Contact
- Androidx学习笔记(22)-- 动态创建TextView展示数据库的数据
- Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析
- C语言指针要点
- 【Hibernate】Hibernate的集合映射(Set、List、Array、Map、Bag)
- <LeetCode OJ> 238. Product of Array Except Self
- 由子网掩码字符串转换成长度前缀的代码示例
- 今天开 CSDN 博客
- 封装cstring实现一个c++字符串处理类
- 华为oj 判断两个IP是否属于同一子网
- Numpy攻略系列:高级索引机制之位置列表型索引,布尔型索引
- css学习之id和class选择器
- apk安装与卸载
- FFMpeg将YUV转码为H264