Leetcode:NO.238 除自身以外数组的乘积

题目

给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]
提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。

说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)

链接:https://leetcode-cn.com/problems/product-of-array-except-self

解题记录

  • 正常逻辑是的到数组中所有数的乘积,然后除以num[i]就是要求是值,但是该题要求不能使用除法
  • 那可以构建两个数组一个存储i左边乘积,一个存储i右边乘积,然后两个数组的数相乘即可求得结果
/**
 * @author ffzs
 * @describe
 * @date 2020/6/4
 */
public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] left = new int[len], right = new int[len], res = new int[len];
        left[0] = nums[0];
        right[len-1] = nums[len-1];
        for (int i = 1; i < len; ++i) {
            left[i] = left[i-1]*nums[i];
            right[len-1-i] = right[len-i]*nums[len-1-i];
        }
        res[0] = right[1];
        res[len-1] = left[len-2];
        for (int i = 1; i < len-1; i++) {
            res[i] = left[i-1]*right[i+1];
        }
        return res;
    }
}

在这里插入图片描述

进阶

  • 要求使用常数的空间
  • 不将左右值先构建好,计算左边的时候直接在返回值中,然后在乘上右边
/**
 * @author ffzs
 * @describe
 * @date 2020/6/4
 */
public class Solution2 {
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] res = new int[len];
        res[0] = 1;
        for (int i = 1; i < len; i++) {
            res[i] = res[i-1] * nums[i-1];
        }
        int tmp = 1;
        for (int i = len-1; i >= 0 ; i--) {
            res[i] *= tmp;
            tmp *= nums[i];
        }
        return res;
    }
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章