面试经典150题——Day13

文章目录

一、题目

238. Product of Array Except Self

Given an integer array nums, return an array answer such that answeri is equal to the product of all the elements of nums except numsi.

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:

Input: nums = 1,2,3,4

Output: 24,12,8,6

Example 2:

Input: nums = -1,1,0,-3,3

Output: 0,0,9,0,0

Constraints:

2 <= nums.length <= 105

-30 <= numsi <= 30

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

题目来源:leetcode

二、题解

由于题目中规定不能使用除法,因此使用left和right两个数组存储nums中索引为i的元素左侧和右侧所有元素的乘积。注意vector中的初始化方法。

cpp 复制代码
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> left(n,0);
        vector<int> right(n,0);
        vector<int> res;
        for(int i = 0;i < n;i++){
            if(i == 0) left[i] = 1;
            else left[i] = left[i-1] * nums[i-1];
        }
        for(int i = n - 1;i >= 0;i--){
            if(i == n-1) right[i] = 1;
            else right[i] = right[i+1] * nums[i+1];
        }
        for(int i = 0;i < n;i++){
            res.push_back(left[i] * right[i]);
        }
        return res;
    }
};
相关推荐
Terra.K1 分钟前
高精度阶乘求和模板深度解析
开发语言·c++·算法
智码看视界13 分钟前
C++智能指针全景剖析及面试20问
开发语言·c++·深度学习·面试·内存管理·智能指针
Peregrine91 小时前
C++ - > 类和对象
java·c++·算法
Gigavision2 小时前
DEAP数据集 2026最新Transformer算法 DEAP 数据集 下载
深度学习·算法·transformer
夜之眷属2 小时前
PriorityQueue:for-each 遍历和 poll 取出,顺序一样吗?
java·服务器·数据结构·后端·算法
触底反弹2 小时前
🎯 LangSmith 学习与面试全攻略:从 Agent「盲盒」到全链路观测与量化评估
人工智能·面试
一tiao咸鱼2 小时前
还在手动海投?我做了个 AI 求职助手,自动筛选 BOSS 职位再精准投递
前端·后端·面试
‎ദ്ദിᵔ.˛.ᵔ₎3 小时前
c++11:fuction包装器
开发语言·c++
思维新观察3 小时前
三星 Galaxy Tab S12 系列:大屏 AI 平板,兼顾轻薄与生产力
数据结构·人工智能·电脑
地平线开发者3 小时前
不是线程越多越快:用 hrt_model_exec 在 征程6M 上给 YOLOv5x 建立性能基线
算法