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;
        }
    }
  • 相关阅读:
    正确率、召回率和 F 值
    柯西序列 转自http://blog.sina.com.cn/coopld
    web用户非正常退出的问题
    uploadify上传的文件
    10270 : 青蛙的游戏
    10117 : 数独游戏
    10101 : 正面交锋
    10049 : 凯的菱形
    DARE YOU CLICK ME???(你敢点我吗???)
    高精度专辑(1码题库)
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5320204.html
Copyright © 2011-2022 走看看