码迷,mamicode.com
首页 > 其他好文 > 详细

238. Product of Array Except Self

时间:2018-11-10 23:52:17      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:col   sel   .com   elf   元素   res   com   变量   bubuko   

一、题目

  1、审题

  技术分享图片

  2、分析

    给出一个整形数组,用另一个数组存储所给数组的除去当前下标元素外的所有元素的乘积。尝试用 O(n) 时间复杂度,常数额外空间。

 

二、解答

  1、思路

    方法一、

      ① 新建数组 result,使用循环,为 result 赋值, result[i] = nums[0] * nums[1] * ... * nums[i-1] 。

      ② 采用新的循环,从后向前遍历nums,用初值为 1 的变量 right 记录从nums中遍历的元素的乘积。

      ③ 将 right 每次更新的值乘入 result [i];

    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] result = new int[len];
        result[0] = 1;
        for (int i = 1; i < len; i++) // result[i] = nums[0] * nums[1] * ... * nums[i-1] 
            result[i] = result[i-1] * nums[i-1];
        
        int right = 1;
        for (int i = len - 1; i >= 0; i--) {
            result[i] *= right; 
            right *= nums[i];
        }
        
        return result;
    }

 

238. Product of Array Except Self

标签:col   sel   .com   elf   元素   res   com   变量   bubuko   

原文地址:https://www.cnblogs.com/skillking/p/9940891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!