Python程式:計算已排序列表中每對數字絕對差之和


假設我們有一個名為nums的已排序數字列表,我們需要找到給定列表中每對數字之間絕對差的總和。這裡我們將(i, j)和(j, i)視為不同的對。如果答案非常大,則將結果模10^9+7。

因此,如果輸入類似於nums = [2, 4, 8],則輸出將為24,因為|2 - 4| + |2 - 8| + |4 - 2| + |4 - 8| + |8 - 2| + |8 - 4|。

為了解決這個問題,我們將遵循以下步驟:

  • m = 10^9 + 7

  • total := 0

  • 對於 i 從0到nums的大小,執行:

    • total := (total + (i * nums[i] - (nums的大小 - 1 - i) * nums[i])) mod m

  • 返回 (2 * total) mod m

讓我們來看下面的實現,以便更好地理解:

示例

 線上演示

class Solution:
   def solve(self, nums):
      m = 10**9 + 7
      total = 0
      for i in range(len(nums)):
         total += (i*nums[i] - (len(nums) - 1 - i)*nums[i]) % m
      return (2*total) % m
ob = Solution()
nums = [2, 4, 8]
print(ob.solve(nums))

輸入

[2, 4, 8]

輸出

24

更新於:2020年10月7日

173 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.