[LeetCode]238. Product of Array Except Self
来源:互联网 发布:js怎么给textarea赋值 编辑:程序博客网 时间:2024/05/16 18:32
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 ofnums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
这道题给定我们一个数组,让我们返回一个新数组,对于每一个位置上的数是其他位置上数的乘积,并且限定了时间复杂度O(n),并且不让我们用除法。如果让用除法的话,那这道题就应该属于Easy,因为可以先遍历一遍数组求出所有数字之积,然后除以对应位置的上的数字。但是这道题禁止我们使用除法,那么我们只能另辟蹊径。我们可以先遍历一遍数组,每一个位置上存之前所有数字的乘积。那么一遍下来,最后一个位置上的数字是之前所有数字之积,是符合题目要求的,只是前面所有的数还需要在继续乘。我们这时候再从后往前扫描,每个位置上的数在乘以后面所有数字之积,对于最后一个位置来说,由于后面没有数字了,所以乘以1就行。参见代码如下:
#include<iostream>#include<vector> using namespace std;vector<int> productExceptSelf(vector<int>& nums) { int len=nums.size(),right=1; vector<int> res(len,1); for(int i=1;i<len;i++) res[i]=res[i-1]*nums[i-1]; for(int i=len-1;i>=0;i--) { res[i]=right*res[i]; right=right*nums[i]; } return res; }int main(){vector<int> numbers;numbers.push_back(1);numbers.push_back(2);numbers.push_back(3);numbers.push_back(4);numbers=productExceptSelf(numbers);for(int i=0;i<numbers.size();i++)cout<<numbers[i]<<'\0';}
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
- 大数处理----大数相加
- 闲着做一道内推试题
- 不想丑陋之实现动态url
- uva10214 Trees in a Wood.
- [读书笔记] 深入探索C++对象模型-第四章-Function语义学(上)
- [LeetCode]238. Product of Array Except Self
- 回溯法经典问题-八皇后
- 学习Javascript总结--易混淆的概念
- 5.javascript 对象继承 ---组合模式
- [cas]Tomcat配置https环境
- 软件测试:原理、方法与管理(读书笔记1)
- 2016大连网络赛1006
- ios 多线程的一些方法使用
- 大数处理---大数相减