面试经典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;
    }
};
相关推荐
cvby4 分钟前
C++11
开发语言·c++
Phil3239 分钟前
多智能体不是越多越好:Google《Towards a Science of Scaling Agent Systems》论文深度解读
算法
6Hzlia10 分钟前
【Classic 150 刷题计划】 LeetCode 26. 删除有序数组中的重复项 | C++ 快慢双指针经典模板
c++·算法·leetcode
huang57914743 分钟前
基于滑动窗口的流式数据算法优化思路3
算法
Ulyanov1 小时前
AudioVision Pro:基于 PySide6 + sounddevice 的实时音频可视化播放器设计
python·算法·音视频
夜不会漫长1 小时前
C++:类和对象(2)
java·javascript·c++
土司大王1 小时前
LeetCode hot100——74.搜索二维矩阵:Java 二分模板
java·算法·leetcode
无小道1 小时前
C++ 中 `explicit` 关键字详解:彻底理解隐式类型转换
c++·explicit
蒸蒸yyyyzwd1 小时前
cpp 选手秋招学习笔记 day34
c++·八股
tyler_download1 小时前
揉扁搓圆transformer架构:NAG优化器算法详解
深度学习·算法·transformer