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;
        }
    }
  • 相关阅读:
    IO流(读取键盘录入)
    IO 流 自定义字节流的缓冲区-read 和write 的特点
    IO流 字节流的缓冲区
    IO流 拷贝图片
    IO流-字节流File读写操作
    IO流 带行号的缓冲区
    IO流(装饰设计模式)
    IO流-ReadLine方法的原理 自定义BufferedReader
    IO流 Buffered 综合练习
    IO流 BufferedWriter
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11881034.html
Copyright © 2011-2022 走看看