LeetCode-Product_of_Array_Except_Self

题目:

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

 

翻译:

给定一个含有n个数字的数组nums,其中n>1,返回一个output数组其中output[i]等于nums中除了nums[i]之外的所有元素的乘积。

例子:

输入:  [1,2,3,4]
输出: [24,12,8,6]

注意: 请解决这个问题不用除法,并且控制时间复杂度在O(n)范围。

 

思路:

http://www.cnblogs.com/grandyang/p/4650187.html 中说的很明确,解法相当巧妙,用某个数字前面所有数字的乘积,同时也知道它后面所有的数乘积,那么二者相乘就是我们要的结果。

 

C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
	vector<int> productExceptSelf(vector<int>& nums) {
		int n = nums.size();
		vector<int> forward(n, 1), backward(n, 1), result(n);
		for (int i = 0; i < n - 1; i++) {
			forward[i + 1] = forward[i] * nums[i];
		}
		for (int i = n - 1; i > 0; i--) {
			backward[i - 1] = backward[i] * nums[i];
		}
		for (int i = 0; i < n; i++) {
			result[i] = forward[i] * backward[i];
		}
		return result;
	}
};

int main()
{
	Solution s;
	vector<int> nums = { 1,2,3,4 };
	vector<int> result = s.productExceptSelf(nums);
	for (int i = 0; i < result.size(); i++) {
		cout << result[i] << " ";
	}
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值