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
        }
    }
  • 相关阅读:
    command injection命令注入
    使用burp进行brute force破解
    vim 常用命令
    mysql.ini 配置
    便捷的 chrome/Firefox扩展
    canves 图片旋转 demo
    lucene 学习一
    php 命令行方式运行时 几种传入参数的方式
    mysql 命令行参数
    java 实现WebService 以及不同的调用方式
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13443824.html
Copyright © 2011-2022 走看看