238——Product of Array Except Self(数组,用空间换时间)
2015-07-22 09:46
429 查看
Product of Array Except Self
Total Accepted: 4824 Total Submissions: 13439My SubmissionsQuestion Solution
Given an array of n integers where n > 1,
nums, return an array
outputsuch that
output[i]is equal to the product of all the elements of
numsexcept
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.)
Hide Tags
Array
Hide Similar Problems
(H) Trapping Rain Water (M) Maximum Product Subarray
这道题要求我们求出一个数组中每一个数的除了它本身之外的其它多有数的乘积,所以采用两个另外的数组来存取,vec1【i】为0,1,2.。。。i-1的乘积
vec2【i】为i+1,i+2。。。n-1的乘积,再依次求乘积
#include<iostream> #include<vector> using namespace std; vector<int> productExceptSelf(vector<int>& nums) { vector<int> vec; if(nums.empty()) return vec; if(nums.size()==1) return nums; vector<int> vec1=nums; vector<int> vec2=nums; int n=nums.size(); vec1[0]=1; int re=1; for(int i=0;i<n-1;i++) { re*=nums[i]; vec1[i+1]=re; } vec2[n-1]=1; re=1; for(int i=n-1;i>0;i--) { re*=nums[i]; vec2[i-1]=re; } for(int i=0;i<n;i++) { vec.push_back(vec1[i]*vec2[i]); } return vec; } int main() { int ary[10]={1,2,3}; vector<int> vec(ary,ary+3); }
相关文章推荐
- 雀巢归巢,还能和年轻人的味蕾好好说话吗?
- [c语言]宏中 #和##的用法
- 启动自己浏览器app的方法
- C++中指针学习记录
- Running OFBiz
- ofbiz加载入eclipse
- jQuery图表开源软件
- android 获取Service(服务)的运行状态
- 基于飞思卡尔i.MX 6DualLite 开发板的触摸屏调试
- IOS中UIview需要知道的一些事情:setNeedsDisplay、setNeedsLayout
- js验证和PHP验证用户输入的区别
- SQL连接查询,子查询,表聚合
- 使用JavaScript的Canvas模拟CSS3中的background-size:cover;
- 查看yarn当前运行任务列表
- Redis 集群解决方案 Codis
- java 转成字符串 json 数组和迭代
- POJ 2531-Network Saboteur(DFS)
- Android在使用WebView的时候需要后退多步
- Hadoop学习笔记(准备与安装)
- php中mysql语句中如果有变量,该如何连接字符串