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
        }
    }
  • 相关阅读:
    多线程开发技术基础
    Asp.Net MVC 进阶篇:路由匹配 实现博客路径 和文章路径
    详解 ManualResetEvent
    Http状态码完整说明
    Javascript 封装问题
    网络爬虫的C++程序
    闭包
    算法框架与问题求解
    SQLSERVER用无中生有的思想来替代游标
    Citrix 服务器虚拟化之四 Xenserver资源池
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13443824.html
Copyright © 2011-2022 走看看