• 【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 }
     
  • 相关阅读:
    再见了,正则表达式
    深入理解 Python 描述符
    并发-ScheduledThreadPoolExecutor
    ScheduledExecutorService用法
    常见限流算法总结
    常见集合类的复杂度
    并发-ConcurrentHashMap 1.7和1.8的区别
    并发-HashMap在jdk1.8也会出现死循环
    并发-Hashmap 1.7和1.8有哪些区别
    并发-HashMap与红黑树-todo
  • 原文地址:https://www.cnblogs.com/QingHuan/p/5046507.html
Copyright © 2020-2023  润新知