面试经典150题——Day13

文章目录

一、题目

238. Product of Array Except Self

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

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 <= nums[i] <= 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;
    }
};
相关推荐
Freshman小白3 小时前
python算法打包为docker镜像(边缘端api服务)
python·算法·docker
mit6.8243 小时前
[VT-Refine] Simulation | Fine-Tuning | docker/run.sh
算法
朴shu3 小时前
Delta数据结构:深入剖析高效数据同步的奥秘
javascript·算法·架构
野生技术架构师3 小时前
牛客网Java 高频面试题总结(2025最新版)
java·开发语言·面试
持梦远方4 小时前
【C++日志库】启程者团队开源:轻量级高性能VoyLog日志库完全指南
开发语言·c++·visual studio
mit6.8244 小时前
博弈dp|凸包|math分类
算法
王中阳Go4 小时前
又整理了一场真实Golang面试复盘!全是高频坑+加分话术,面试遇到直接抄
后端·面试·go
JavaGuide4 小时前
今年小红书后端开出了炸裂的薪资!
后端·面试
许长安4 小时前
C++中指针和引用的区别
c++·经验分享·笔记
Shinom1ya_4 小时前
算法 day 41
数据结构·算法·leetcode