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

    package LeetCode_238
    
    /**
     * 238. Product of Array Except Self
     * https://leetcode.com/problems/product-of-array-except-self/description/
     * Given an array nums of n integers where n > 1,
     * return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
    
    Example:
    Input:  [1,2,3,4]
    Output: [24,12,8,6]
    Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array(including the whole array) fits in a 32 bit integer.
    
    Note: Please solve it without division and in O(n).
    
    Follow up:
    Could you solve it with constant space complexity?
    (The output array does not count as extra space for the purpose of space complexity analysis.)
     * */
    class Solution {
        /*
        * solution 1: prefix_array and suffix_array, Time complexity:O(n), Space complexity:O(n);
        * */
        fun productExceptSelf(nums: IntArray): IntArray {
            val n = nums.size
    
            val prefixArray = IntArray(n,{1})
            val suffixArray = IntArray(n,{1})
    
            var prefixProduct = 1
            for (i in 1 until n) {
                prefixProduct *= nums[i-1]
                prefixArray[i] = prefixProduct
            }
    
            for (i in n - 1 downTo 1) {
                suffixArray[i-1] = suffixArray[i] * nums[i]
            }
    
            val result = IntArray(n)
            for (i in 0 until n){
                result[i] = prefixArray[i] * suffixArray[i]
            }
    
            return result
        }
    }
  • 相关阅读:
    起点中文网小说爬取-etree,xpath,os
    拉勾网爬虫--待改正
    破解有道词典翻译-版本二
    pycharm错误:11001
    自动化selenium 测试之道(一)
    valgrind 详细说明
    sar命令使用详解
    Linux CPU实时监控mpstat命令详解
    Linux IO实时监控iostat命令详解
    RPM安装命令总结
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13443824.html
Copyright © 2011-2022 走看看