鱼C论坛

 找回密码
 立即注册
查看: 1538|回复: 0

[学习笔记] leetcode 238. Product of Array Except Self

[复制链接]
发表于 2019-9-17 11:50:41 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. 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].

  2. Example:

  3. Input:  [1,2,3,4]
  4. Output: [24,12,8,6]
  5. Note: Please solve it without division and in O(n).

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

  1. class Solution {
  2.     public int[] productExceptSelf(int[] nums) {
  3.         int mul = 1;
  4.         int[] res = new int[nums.length];
  5.         for(int i = 0; i<nums.length; i++){
  6.             res[i] = 1;
  7.         }
  8.         for(int i = 0; i< nums.length; i++){
  9.             res[i] = res[i] * mul;
  10.             mul = mul * nums[i];
  11.          }
  12.         mul = 1;
  13.         for(int i = nums.length -1 ; i>=0 ; i--){
  14.             res[i] = res[i] * mul;
  15.             mul = mul * nums[i];
  16.         }
  17.         
  18.         return res;
  19.     }
  20. }
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-7 07:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表