zoukankan      html  css  js  c++  java
  • 【08_238】Product of Array Except Self

    Product of Array Except Self

    Total Accepted: 26470 Total Submissions: 66930 Difficulty: Medium

    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 numsexcept 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.)

    限定了不能用除法,和时间复杂度。

    但Follow up我没太懂,是不允许申请额外的空间吗?

    这次本来想用位运算中的异或运算写,但是发现那样有固有缺陷——对负数不起效果。而且越改越臃肿。

    最后在Discuss中找到一个好方法, 这个方法申请了额外的数组。

    优点:

    1. 得到数组中新的一个数字时,借助了上一位,从而不用再次遍历整个数组
    2. 方法很巧妙

    下面是看完解答后自己写的:

    Java语言写的

     1 public class Solution {
     2     public int[] productExceptSelf(int[] nums) {
     3         int[] res = new int[nums.length];
     4         res[0] = 1;
     5         for (int i = 1; i < nums.length; i++)  {
     6             res[i] = res[i - 1] * nums[i - 1];
     7         }
     8         int right = 1;
     9         for (int i = nums.length - 1; i >= 0; i--)  {
    10             res[i] *= right;
    11             right *= nums[i];
    12         }
    13         return res;
    14     }
    15 }
     
  • 相关阅读:
    final关键字
    this and super
    java 内存分析之static
    java 内存分析之this
    java 内存分析之方法返回值二
    java 内存分析之方法返回值及匿名对象一
    java 内存分析之构造方法执行过程
    java 内存分析之堆栈空间
    java jvm概述及工作过程中的内存管理
    java 编译器
  • 原文地址:https://www.cnblogs.com/QingHuan/p/5046507.html
Copyright © 2011-2022 走看看