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;
        }
    }
  • 相关阅读:
    C语言网 蓝桥杯 1117K-进制数
    C语言网蓝桥杯1116 IP判断
    LeetCode 面试题14- II. 剪绳子 II
    LeetCode 面试题06. 从尾到头打印链表
    LeetCode 面试题05. 替换空格
    LeetCode 面试题04. 二维数组中的查找
    LeetCode 面试题03. 数组中重复的数字
    LeetCode 3. 无重复字符的最长子串
    LeetCode 202. 快乐数
    LeetCode 154. 寻找旋转排序数组中的最小值 II
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5320204.html
Copyright © 2011-2022 走看看