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

[LeetCode] 面试题64. 求1+2+…+n

时间:2020-06-05 00:34:59      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:png   res   col   cte   ble   联系   方法   alt   元素   

yi开始自己想的

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res=new int[nums.length];
        int sum=1;
        for(int num:nums){
            sum =sum*num;
        }
        for(int i=0;i<nums.length;i++){
            res[i]=sum/nums[i];
        }
        return res;
    }
}

没考虑到可能会有0在分母上

牛了这个方法:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int k = 1;
        for(int i = 0; i < res.length; i++){
            res[i] = k;
            k = k * nums[i]; // 此时数组存储的是除去当前元素左边的元素乘积
        }
        k = 1;
        for(int i = res.length - 1; i >= 0; i--){
            res[i] *= k; // k为该数右边的乘积。
            k *= nums[i]; // 此时数组等于左边的 * 该数右边的。
        }
        return res;
    }
}

作者:LDouble
链接:https://leetcode-cn.com/problems/product-of-array-except-self/solution/cheng-ji-dang-qian-shu-zuo-bian-de-cheng-ji-dang-q/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

技术图片

 

[LeetCode] 面试题64. 求1+2+…+n

标签:png   res   col   cte   ble   联系   方法   alt   元素   

原文地址:https://www.cnblogs.com/doyi111/p/13047305.html

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