zoukankan      html  css  js  c++  java
  • [LC] 238. Product of Array Except Self


    Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Example:

    Input:  [1,2,3,4]
    Output: [24,12,8,6]
    

    Note: Please solve it without division and in O(n).

    Follow up:
    Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

    class Solution {
        public int[] productExceptSelf(int[] nums) {
            if (nums == null || nums.length == 0) {
                return nums;
            }
            int[] resArr = new int[nums.length];
            resArr[0] = 1;
            for (int i = 1; i < nums.length; i++) {
                resArr[i] = resArr[i - 1] * nums[i - 1];
            }
            
            int right = 1;
            for (int i = nums.length - 1; i >= 0; i--) {
                resArr[i] *= right;
                right *= nums[i];
            }
            return resArr;
        }
    }
    public class Solution {
        /**
         * @param nums: an array of integers
         * @return: the product of all the elements of nums except nums[i].
         */
        public int[] productExceptSelf(int[] nums) {
            // write your code here
            int len = nums.length;
            int[] prefix = new int[len];
            int[] suffix = new int[len];
            for (int i = 0; i < len; i++) {
                if (i == 0) {
                    prefix[i] = nums[i];
                    continue;
                }
                prefix[i] = prefix[i - 1] * nums[i];
            }
            for(int i = len - 1; i >= 0; i--) {
                if (i == len - 1) {
                    suffix[i] = nums[i];
                    continue;
                }
                suffix[i] = suffix[i + 1] * nums[i];
            }
            int[] res = new int[len];
            for (int i = 0; i < len; i++) {
                if (i == 0) {
                    res[i] = suffix[i + 1];
                    continue;
                }
                if (i == len - 1) {
                    res[i] = prefix[i - 1];
                    continue;
                }
                res[i] = prefix[i - 1] * suffix[i + 1];
            }
            return res;
        }
    }
  • 相关阅读:
    linux命令学习之:cd
    SSH原理与运用
    java遍历当前会话所有Session
    spring+quartz报错:Table 'XXXX.QRTZ_TRIGGERS' doesn't exist
    python检测编码
    python安装模块
    python网络爬虫
    系统编码 python编码
    python 中文路径
    python读取文件乱码
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11881034.html
Copyright © 2011-2022 走看看