zoukankan      html  css  js  c++  java
  • [LeetCode] 238. 除自身以外数组的乘积

    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)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    造出最好的 CMS 轮子
    搭建开发框架Express,实现Web网站登录验证
    QueryOver<T>
    NVelocity
    .NET 相依性注入
    Unity 3.5
    java socket 的参数选项解读(转)
    换种方式去分页(转)
    上海市居住证办理材料及流程
    java动态代理
  • 原文地址:https://www.cnblogs.com/doyi111/p/13047305.html
Copyright © 2011-2022 走看看