算法設計與應用基礎:第一週(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]累乘之前所有的目的



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