面试经典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;
    }
};
相关推荐
胡萝卜术13 小时前
力扣5. 最长回文子串
前端·javascript·面试
jinyishu_14 小时前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm14 小时前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
触底反弹15 小时前
🔥 从零搭建 RAG 知识库:爬虫→分词→向量化→检索,一步都不能错
javascript·人工智能·面试
什巳15 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
hold?fish:palm17 小时前
RDB全量快照备份
c++·redis·后端
什巳17 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_7968265217 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
盐焗鹌鹑蛋18 小时前
【C++】C++11:列表初始化、声明、STL升级
c++
巧克力男孩dd19 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法