zoukankan      html  css  js  c++  java
  • Multiplication of numbers

    Questin:

    There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. Solve it without division operator and in O(n).

    For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1].

    Example:

    A: {4, 3, 2, 1, 2}
    OUTPUT: {12, 16, 24, 48, 24}

    思路:

    可以使用迭代累计。output[i]=a[i]左边的乘积 x a[i]右边的乘积,所以,我们可以分两个循环,第一次先把A[i]左边的乘积放在Output[i]中,第二次把A[i]右边的乘积算出来;也可以直接放在一个循环中,只不过需要同时计算左边的乘积和右边的乘积。(当然也可分开计算A[i]左边和右边的数据,这样容易理解!最后将左边和右边的相乘即可

    代码如下:

    void Multiplication_Array(int A[], int OUTPUT[], int n) {
      int left = 1;
      int right = 1;
      for (int i = 0; i < n; i++)
          OUTPUT[i] = 1;
      for (int i = 0; i < n; i++) {
          OUTPUT[i] *= left;
          OUTPUT[n - 1 - i] *= right;
          left *= A[i];
          right *= A[n - 1 - i];
      }
    }
    

    void Mutiplication_Array2()
    {
        int *X = new int[n];
        int *Y = new int[n];
        // Create X
        X[0] = 1;
        for(int i = 1; i < n; i++){
            X[i] = X[i-1] * A[i-1];
        }
        // Create Y
        Y[n-1] = 1;
        for(int i = n-2; i >= 0; i--){
            Y[i] = Y[i+1] * A[i+1];
        }
        // Create Out
        for(int i = 0; i < n; i++){
            out[i] = X[i] * Y[i];
        }
        // Delete X and Y
        delete[] X;
        delete[] Y;
    }
  • 相关阅读:
    Dubbo——服务目录
    Dubbo——服务调用过程
    Dubbo——服务引用
    Dubbo——服务发布原理
    Dubbo——SPI及自适应扩展原理
    Zookeeper——Watcher原理详解
    Zookeeper——基本使用以及应用场景(手写实现分布式锁和rpc框架)
    Zookeeper——分布式一致性协议及Zookeeper Leader选举原理
    分布式架构概述及设计
    设计之禅——访问者模式
  • 原文地址:https://www.cnblogs.com/ywl925/p/3737008.html
Copyright © 2011-2022 走看看