面试经典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;
    }
};
相关推荐
文丑颜不良啊1 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw1 小时前
C++ union 的一种妙用法
开发语言·c++
罗西的思考2 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊2 小时前
LeetCode3101~3120题目解析
java·leetcode
ShineWinsu3 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步4 小时前
string的实现(1)
c++·笔记·visual studio
kyle~6 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
敲上瘾6 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯7 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好8 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频