zoukankan      html  css  js  c++  java
  • [Facebook] Products of all elements

    Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.
    Input : [1, 2, 3, 4, 5]
    Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
          = [120, 60, 40, 30, 24]
    You must do this in O(N) without using division.

    [Thoughts]
    An explaination of polygenelubricants method is: The trick is to construct the arrays (in the case for 4 elements)
    {              1,         a[0],    a[0]*a[1],    a[0]*a[1]*a[2],  }
    { a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, }
    Both of which can be done in O(n) by starting at the left and right edges respectively.
    Then multiplying the two arrays element by element gives the required result
    My code would look something like this:
    int a[N] // This is the input
    int products_below[N];
    p=1;
    for(int i=0;i<N;++i)
    {
    products_below[i]=p;
    p*=a[i];
    }

    int products_above[N];
    p=1;
    for(int i=N-1;i>=0;--i)
    {
    products_above[i]=p;
    p*=a[i];
    }

    int products[N]; // This is the result
    for(int i=0;i<N;++i)
    {
    products[i]=products_below[i]*products_above[i];
    }

    If you need to be O(1) in space too you can do this (which is less clear IMHO)
    int a[N] // This is the input
    int products[N];

    // Get the products below the curent index
    p=1;
    for(int i=0;i<N;++i)
    {
    products[i]=p;
    p*=a[i];
    }

    // Get the products above the curent index
    p=1;
    for(int i=N-1;i>=0;--i)
    {
    products[i]*=p;
    p*=a[i];
    }

  • 相关阅读:
    7. Scrapy的高级用法
    6. Scrapy的基本用法
    5. 基于Selenium实现爬虫
    4. 异步爬虫
    3. 数据解析
    2. requests的使用
    1. 爬虫概述
    03-Servlet初识
    Flask框架基础(1)
    登录mysql时,报错ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078909.html
Copyright © 2011-2022 走看看