首页 文章

将列表映射到除当前索引之外的元素的乘积,而不使用除法

提问于
浏览
0

我'm doing some exercies in Haskell, and this is the current one I'正在https://leetcode.com/problems/product-of-array-except-self/工作 .

给定n个整数的数组,其中n> 1,nums,返回一个数组输出,使得output [i]等于除nums [i]之外的所有nums元素的乘积 . 在没有除法和O(n)的情况下解决它 . 例如,给定[1,2,3,4],返回[24,12,8,6] .

我能够通过分工很容易地做到这一点:

import Data.List (foldl1')

productOfArray :: [Int] -> [Int]
productOfArray xs = f <$> xs
  where p = foldl1' (*)
        f = div (p xs)

但我不太确定如何在没有分工的情况下接近它 . 命令式方法是映射到当前索引左侧所有数字的乘积乘以当前索引右侧的所有数字,但在Haskell中,我不太清楚如何概念化它 .

1 回答

  • 1

    您可以使用 tailsinits 函数执行此操作,这些函数返回Nth之后和之前的所有元素 .

    > tails [1,2,3,4]
    [[1,2,3,4], [2,3,4], [3,4], [4]]
    

    请注意,如果删除第一个值,则这正是在缺少元素之后必须乘以的值 .

    > tail $ tails [1,2,3,4]
    [[2,3,4], [3,4], [4]]
    

    inits 将返回缺失数字之前的值

    > heads [1,2,3,4]
    [[], [1], [1,2], [1,2,3], [1,2,3,4]]
    

    最后,使用product函数和zipwith进行最终的乘法运算 .

    zipWith (*) (map product $ inits [1,2,3,4]) (map product $ tail $ tails [1,2,3,4])
    

相关问题