栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode-238. Product of Array Except Self [C++][Java]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode-238. Product of Array Except Self [C++][Java]

LeetCode-238. Product of Array Except Selfhttps://leetcode.com/problems/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 <= 10^5-30 <= nums[i] <= 30The 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.)

解题思路 【C++】
class Solution {
public:
    vector productExceptSelf(vector& nums) {
        int n = nums.size(), left = 1, right = 1;
        vector products(n, 1);
        for (int i=1; i=0; i--) {
            right *= nums[i + 1];
            products[i] *= right;
        }
        return products;
    }
};

【Java】
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length, left = 1, right = 1;
        int[] products = new int[n];
        Arrays.fill(products, 1);
        for (int i=1; i=0; i--) {
            right *= nums[i + 1];
            products[i] *= right;
        }
        return products;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/778149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号