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;
    }
}

在這裏插入圖片描述

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