zoukankan      html  css  js  c++  java
  • Leetcode 238 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.)

    public class S238 {
        public int[] productExceptSelf(int[] nums) {
            //左右两个数组分别表示nums[i]左右两边的乘积,那么rets[i]=left[i]*right[i]
            //判断是否为零反而时间变长,本来想法是判断到零就可以结束循环(零以后的数除自己以外的乘积都为零),减少复杂度
    /*        int []left = new int[nums.length];
            left[0] = 1;
            int []right = new int[nums.length];
            right[nums.length-1] = 1;
            int []rets = new int[nums.length];
            for(int i = 1;i<nums.length;i++){
                left[i] = left[i-1]*nums[i-1]; 
                right[nums.length-i-1] = right[nums.length-i]*nums[nums.length-i];
                if(i>nums.length/2-1){
                    rets[i] = left[i]*right[i];
                }
                if(nums[i] == 0){
                    break;
                }
            }
            for(int i = 0;i<nums.length/2;i++){
                rets[i] = left[i]*right[i];
                if(nums[i] == 0){
                    break;
                }
            }
            return rets;*/
            //减小空间复杂度的方法,同时也降低了运行时间,是否判断零没有影响
            int []rets = new int[nums.length];
            rets[nums.length-1] = 1;
            //先求出每个数右侧乘积
            for(int i = nums.length-2;i>=0;i--){
                rets[i] = rets[i+1]*nums[i+1];
                if(nums[i] == 0){
                    break;
                }
            }
            //再从左往右,求左侧积的时候用rets保存结果
            int left = 1;
            for(int i = 0;i<nums.length;i++){
                rets[i] *= left;
                left *= nums[i];
            }
            return rets;
        }
    }
  • 相关阅读:
    隐马尔科夫模型(HMM)
    各大IT企业招聘所须要求技能
    Java NIO和IO的主要差别
    Css 选择器总结
    程序猿生存定律-六个程序猿的故事(3)
    JVM学习心得
    APUE读书笔记-第14章-高级I/O
    《Word排版艺术》读后感,兼谈LaTeX
    LaTeX:Figures, Tables, and Equations 插入图表和公式
    LaTeX 的对参考文献的处理
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5320204.html
Copyright © 2011-2022 走看看