zoukankan      html  css  js  c++  java
  • Product of Array Except Self

    问题描述

    Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Solve it without division and in O(n).

    For example, given [1,2,3,4], return [24,12,8,6].

    Follow up:
    Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

    解决思路

    1. 使用辅助空间

    为方便理解,使用两个与输入数组同等大小的辅助数组

    首先,从前到后扫描数组,一个数组[i]存储的是除了当前元素外的所有前面元素的乘积;

    然后,从后到前扫描数组,另一个数组[i]存储的是除了当前元素外的所有后面元素的乘积。

    最后将这两个数组的对应位置的元素相乘即可。

    优化后可以省略一个数组和一遍扫描。

    程序

    public class Solution {
        public int[] productExceptSelf(int[] nums) {
            if (nums == null) {
                return null;
            }
            int len = nums.length;
            int[] res = new int[len];
            int[] tmp = new int[len];
            tmp[0] = 1;
            res[0] = 1;
            
            for (int i = 1; i < len; i++) {
                tmp[i] = tmp[i - 1] * nums[i - 1];
                res[i] = tmp[i];
            }
            tmp[len - 1] = 1;
            for (int i = len - 2; i >= 0; i--) {
                tmp[i] = tmp[i + 1] * nums[i + 1];
                res[i] *= tmp[i];
            }
            
            return res;
        }
    }
    

      

  • 相关阅读:
    《信息学奥赛一本通》提高版题解索引
    QUERY [ 单调栈 ]
    [ 模拟退火 ] bzoj3860 平衡点
    [ 考试 ] 7.12
    离线和简单分治
    [ 校内OJ ] NOIP2019模拟赛(九)
    校内模拟考 (一)
    Codeforces 808E
    学习笔记—点分治
    [ 线段树+哈希 ] 反等差数列
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4650485.html
Copyright © 2011-2022 走看看