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

    Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Solve it without division and in O(n).

    For example, given [1,2,3,4], return [24,12,8,6].

    Follow up:
    Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

     
     1 public class Solution {
     2     public int[] productExceptSelf(int[] nums) 
     3     {
     4         int[] array1 = new int[nums.length];
     5         int[] array2 = new int[nums.length];
     6         int[] result = new int[nums.length];
     7 
     8         array1[0]=1;
     9         array2[nums.length-1]=1;
    10         for(int i = 1; i<nums.length;i++)
    11         {
    12             array1[i]=array1[i-1]*nums[i-1];
    13             
    14         }
    15         for(int i=nums.length-2;i>=0;i--)
    16         {
    17             array2[i]=array2[i+1]*nums[i+1];
    18         }
    19         for(int i=0;i<nums.length;i++)
    20         {
    21             result[i]=array1[i]*array2[i];
    22         }
    23         
    24         return result;
    25         
    26         
    27     }
    28 }
  • 相关阅读:
    day10作业
    day9 函数作业
    Python编码及文件练习题
    day10函数命名空间,嵌套,闭包
    Python基础数据类型考试题
    day9 函数
    day8 文件操作
    day7 集合
    day6 编码
    day5 作业自我完成版
  • 原文地址:https://www.cnblogs.com/hygeia/p/4859951.html
Copyright © 2011-2022 走看看