面试经典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;
    }
};
相关推荐
深圳市益普科技有限公司38 分钟前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法
挖井观天39 分钟前
《Java数据结构》第一讲:顺序表
数据结构
努力努力再努力wz1 小时前
【C++高阶系列】C++20 协程底层原理:函数为什么能暂停?从状态机到 Task,彻底串起挂起、恢复与协程调度
开发语言·c++·c++20·1024程序员节
程序员清风2 小时前
算法题中的边界条件、测试与调试
开发语言·算法·kotlin
划破黑暗的第一缕曙光2 小时前
[C++]:4.模板
c++·template·模板·函数模版·类模版
十五年专注C++开发2 小时前
pybind11:一个跨C++和Python平台的编程库
开发语言·c++·python·pybind11
CodeYp20192 小时前
第11讲:stack 和 queue
开发语言·c++·queue·stack
彭亚川Allen2 小时前
从零手搓 RAG 之 Embedding 技术
前端·后端·面试
炘爚2 小时前
数据结构算法总结
数据结构·python·算法
Dageno_AI2 小时前
ChatGPT 不再引用 Reddit 之后,还值得在 Reddit 上做 AI 可见度吗?
算法