算法设计与应用基础:第一周(3)

238. Product of Array Except Self

Description Submission Solutions
  • Total Accepted: 84193
  • Total Submissions: 176822
  • Difficulty: Medium
  • Contributors: Admin

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.)

codes:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
     int n=nums.size();
    int fromBegin=1;
    int fromLast=1;
    vector<int> res(n,1);
    
    for(int i=0;i<n;i++){
        res[i]*=fromBegin;
        fromBegin*=nums[i];
       
    }
    //for(int i=0;i<n;i++)
        //cout<<res[i]<<endl;
    for(int i=n-1;i>=0;i--)
    {
        res[i]*=fromLast;
        fromLast*=nums[i];
    }
    //for(int i=0;i<n;i++)
        //cout<<res[i]<<endl;
    return res;
    }
};

解题思路:主要在于算法中的两层循环,思路借鉴了博客一位大神对于算数组前n项积的方法。第一层循环:利用哨兵值Fromfirst每次res[i]累乘Fromfirst相当于累乘nums[i]之前的数组累积;第二层循环:res[i]每次累乘Fromlast相当于累乘nums[i]之后的数组累积;两层循环之后可得到正确的res值
 	res[i]*=fromBegin;
        fromBegin*=nums[i];
第一行res[i]累乘fromBegin,第二行fromBegin累乘nums[i]以达到res[i]累乘之前所有的目的



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章