国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Product of Array Except Self 題解

2019-11-06 06:15:41
字體:
來源:轉載
供稿:網友

238. PRoduct of Array Except Self

題目描述:

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

題目鏈接:238. Product of Array Except Self

算法描述:

    根據題意,給出一個數組,我們將返回一個結果數組,該結果數組中第 i 個元素的值為除去第 i 個元素的所有其它元素之積。題目要求復雜度控制在 O(n),并且不能用除法。

解決思路:因為第 i 個位置上的值等于 i 位置左邊所有元素乘積與 i 位置右邊所有元素乘積的乘積,因此,我們創建容器 vector<int> left  和 vector<int> right,用它們來存儲左邊元素乘積與右邊元素乘積,如:第 i 個元素左邊乘積為:left[i]=left[i-1]*nums[i-1] ,右邊元素乘積為:right[i]=right[i+1]*nums[i+1]。因此,我們可以用兩個 for 循環完成此次遍歷,最后返回結果  ans[i]=left[i]*right[i]。算法復雜度控制在O(n)。

代碼:

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        vector<int> ans(nums.size(),1);        vector<int> left(nums.size(), 1);        vector<int> right(nums.size(),1);                for(int i=1; i<nums.size(); i++){            left[i]=left[i-1]*nums[i-1];        }        for(int i=nums.size()-2; i>=0; i--){            right[i]=right[i+1]*nums[i+1];        }        for(int i=0; i<nums.size(); i++){            ans[i]=left[i]*right[i];        }                return ans;    }};


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 滦平县| 桂阳县| 钟山县| 双江| 九寨沟县| 顺昌县| 长治县| 天峻县| 庐江县| 申扎县| 鄂伦春自治旗| 集安市| 新邵县| 云龙县| 通海县| 泾源县| 富蕴县| 罗江县| 格尔木市| 巴中市| 白山市| 板桥市| 浏阳市| 河津市| 贡嘎县| 永昌县| 繁昌县| 喜德县| 彭山县| 永宁县| 东光县| 库伦旗| 东乡县| 即墨市| 沂南县| 吉林省| 西城区| 乳源| 西华县| 营山县| 旬阳县|