面试经典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;
    }
};
相关推荐
Tyler_TXZ7 分钟前
C++C语言之——二叉树
c语言·开发语言·数据结构·c++·二叉树
Tisfy17 分钟前
LeetCode 3090.每个字符最多出现两次的最长子字符串:二重循环 / 滑动窗口
算法·leetcode·字符串·题解·模拟·双指针·滑动窗口
-dzk-17 分钟前
【技巧】LC 136.只出现一次的数字
算法·异或
不会代码的小猴31 分钟前
C++新增关键字
开发语言·c++·笔记
专注仿真1 小时前
问答大模型技术方案算法实现-RAPTOR树构建算法与BEG集成使用
python·算法
众人皆醒我独醉1 小时前
AI 工作负载可观测性:DCGM + Prometheus + Grafana
面试·llm·gpu
西门老铁1 小时前
JWT 是什么?三段式结构、签名原理与 6 个安全坑一次讲透
后端·面试
liulilittle2 小时前
并发与内存安全术语:定义、分类与关联
c++·安全·并发·术语
_wyt0012 小时前
从图到树:9道洛谷基础题带你入门树形结构
c++·
zlinear数据采集卡2 小时前
数据采集卡从入门到精通(10):采样率与分辨率的核心关系——反比律、架构分布与过采样
arm开发·嵌入式硬件·算法·fpga开发·架构·开源