★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-qcpnhvin-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array of integers A
, consider all non-empty subsequences of A
.git
For any sequence S, let the width of S be the difference between the maximum and minimum element of S.github
Return the sum of the widths of all subsequences of A. 數組
As the answer may be very large, return the answer modulo 10^9 + 7. 微信
Example 1:ide
Input: [2,1,3]
Output: 6 Explanation: Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6.
Note:spa
1 <= A.length <= 20000
1 <= A[i] <= 20000
給定一個整數數組 A
,考慮 A
的全部非空子序列。code
對於任意序列 S ,設 S 的寬度是 S 的最大元素和最小元素的差。htm
返回 A 的全部子序列的寬度之和。blog
因爲答案可能很是大,請返回答案模 10^9+7。
示例:
輸入:[2,1,3] 輸出:6 解釋: 子序列爲 [1],[2],[3],[2,1],[2,3],[1,3],[2,1,3] 。 相應的寬度是 0,0,0,1,1,2,2 。 這些寬度之和是 6 。
提示:
1 <= A.length <= 20000
1 <= A[i] <= 20000
1 class Solution { 2 func sumSubseqWidths(_ A: [Int]) -> Int { 3 var A = A.sorted(by:<) 4 var c:Int = 1 5 var res:Int = 0 6 var mod:Int = Int(1e9 + 7) 7 let countA:Int = A.count 8 var i:Int = 0 9 while(i < countA) 10 { 11 res = (res + A[i] * c - A[countA - i - 1] * c) % mod 12 i += 1 13 c = (c << 1) % mod 14 } 15 return Int((res + mod) % mod) 16 } 17 }