面试经典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;
    }
};
相关推荐
over6974 小时前
从 LLM 到全栈 Agent:MCP 协议 × RAG 技术如何重构 AI 的“做事能力”
面试·llm·mcp
SuperEugene5 小时前
Vue状态管理扫盲篇:如何设计一个合理的全局状态树 | 用户、权限、字典、布局配置
前端·vue.js·面试
blasit5 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
AI软著研究员6 小时前
程序员必看:软著不是“面子工程”,是代码的“法律保险”
算法
FunnySaltyFish6 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
颜酱7 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
Sailing7 小时前
🚀 别再乱写 16px 了!CSS 单位体系已经进入“计算时代”,真正的响应式布局
前端·css·面试
SuperEugene10 小时前
Vue状态管理扫盲篇:Vuex 到 Pinia | 为什么大家都在迁移?核心用法对比
前端·vue.js·面试
Hilaku10 小时前
我会如何考核一个在简历里大谈 AI 提效的高级前端?
前端·javascript·面试
前端Hardy10 小时前
别再用 $emit 满天飞了!Vue 3 组件通信的 4 种正确姿势,第 3 种 90% 的人不知道
前端·vue.js·面试