[容易]数组剔除元素后的乘积

题目来源:http://www.lintcode.com/zh-cn/problem/product-of-array-exclude-itself/

方法1:直接法

可以accept的程序如下:

 1 class Solution {
 2 public:
 3     /**
 4      * @param A: Given an integers array A
 5      * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
 6      */
 7     vector<long long> productExcludeItself(vector<int> &nums) {
 8         // write your code here
 9         vector<long long> result;
10         for(int i=0;i<nums.size();i++)
11         {
12             long long temp=1;
13             for(int j=0;j<i;j++)
14                 temp*=nums[j];
15             for(int j=i+1;j<nums.size();j++)
16                 temp*=nums[j];
17             result.push_back(temp);
18         }
19         return result;
20     }
21 };

方法2:Time: O(n)   Space: O(1)

可以accept的程序如下:

 1 class Solution {
 2 public:
 3     /**
 4      * @param A: Given an integers array A
 5      * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
 6      */
 7     vector<long long> productExcludeItself(vector<int> &nums) {
 8         // write your code here
 9         vector<long long> left_product(nums.size());
10         left_product[0] = 1;
11         for (int i = 1; i < nums.size(); ++i) {
12             left_product[i] = left_product[i - 1] * nums[i - 1];
13         }
14         long long right_product = 1;
15         for (int i = static_cast<int>(nums.size()) - 2; i >= 0; --i) {
16             right_product *= nums[i + 1];
17             left_product[i] = left_product[i] * right_product;
18         }
19         return left_product;
20     }
21 };

方法3:Time: O(n)   Space: O(n)

可以accept的程序如下:

 1 class Solution {
 2 public:
 3     /**
 4      * @param A: Given an integers array A
 5      * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
 6      */
 7     vector<long long> productExcludeItself(vector<int> &nums) {
 8         // write your code here
 9         vector<long long> left_product(nums.size());
10         vector<long long> right_product(nums.size());
11         vector<long long> product(nums.size());
12         left_product[0] = 1;
13         for (int i = 1; i < nums.size(); ++i) {
14             left_product[i] = left_product[i - 1] * nums[i - 1];
15         }
16         right_product[nums.size() - 1] = 1;
17         for (int j = static_cast<int>(nums.size()) - 2; j >= 0; --j) {
18             right_product[j] = right_product[j + 1] * nums[j + 1];
19         }
20         for (int k = 0; k < nums.size(); ++k) {
21             product[k] = left_product[k] * right_product[k];
22         }
23         return product;
24     }
25 };
posted @ 2016-05-11 22:08  Pearl_zju  阅读(209)  评论(0编辑  收藏  举报