238. Product of Array Except Self
来源:互联网 发布:php面向对象 实战项目 编辑:程序博客网 时间:2024/05/18 02: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 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.)
我的解答:
1.额外空间O(n) 时间复杂度O(1)
2.额外空间O(1) 时间复杂度O(1)
//// main.cpp// 238. Product of Array Except Self//// Created by zjl on 16/6/23.// Copyright © 2016年 zjl. All rights reserved.//#include <iostream>#include <vector>using namespace std;vector<int> productExceptSelf1(vector<int>& nums) { int n = nums.size(); vector<int> formbeg(n+1,1); vector<int> formend(n+1,1); vector<int> res(n,1); for(int i = 1; i <= n; i++){ formbeg[i] = formbeg[i-1]*nums[i-1]; } for(int i = n-1; i >=0; i--){ formend[i] = formend[i+1]*nums[i]; } for(int j = 0; j < n; j++){ res[j] = formbeg[j] * formend[j+1]; } return res;}vector<int> productExceptSelf2(vector<int>& nums) { int n = nums.size(); vector<int>res(n,1); for(int i = 1; i < n; i++){ res[i] = res[i-1]*nums[i-1]; } long long t = 1; for(int j = n-1; j >=0; j--){ res[j] *= t; t *= nums[j]; } return res;}int main(int argc, const char * argv[]) { vector<int> nums = {1,2,3,4}; vector<int> res = productExceptSelf2(nums); for(int i = 0; i < res.size(); i++) cout<<res[i] << " "; cout<<endl; return 0;}
输入: 1,2,3,4
输出:24 12 8 6
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
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- LeetCode 238. Product of Array Except Self
- 关键子工程
- caffe|Fine-tuning for driver
- 浅谈Android实现3D旋转
- docker 入门
- JavaScript中的call()和apply()方法
- 238. Product of Array Except Self
- 网络编程socket(服务端简单模拟)(OC)
- [疯狂Java]面向对象:继承、覆盖、super
- C语言基础 求余运算
- Android项目之仿360手机助手项目
- Qt之QImageReader
- Spark定制班第26课:Spark Streaming的JobGenerator源码图解
- Java:按值传递还是按引用传递详细解说
- Android系统自带样式(@android:style/)