在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of integers Since the answer may be large, return the answer modulo Example 1: Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Note:
给定一个整数数组 由于答案可能很大,因此返回答案模 示例: 输入:[3,1,2,4] 输出:17 解释: 子数组为 [3],[1],[2],[4],[3,1],[1,2],[2,4],[3,1,2],[1,2,4],[3,1,2,4]。 最小值为 3,1,2,4,1,1,2,1,1,1,和为 17。 提示:
Runtime: 524 ms
Memory Usage: 19 MB
1 class Solution { 2 func sumSubarrayMins(_ A: [Int]) -> Int { 3 var stack:[Int] = [Int]() 4 var n:Int = A.count 5 var res:Int = 0 6 var mod:Int = Int(1e9 + 7) 7 var j:Int = 0 8 var k:Int = 0 9 for i in 0...n 10 { 11 while (!stack.isEmpty && A[stack.last!] > (i == n ? 0 : A[i])) 12 { 13 j = stack.removeLast() 14 k = stack.isEmpty ? -1 : stack.last! 15 res = (res + A[j] * (i - j) * (j - k)) % mod 16 } 17 stack.append(i) 18 } 19 return res 20 } 21 } 608ms 1 class Solution { 2 func sumSubarrayMins(_ A: [Int]) -> Int { 3 let m = 1000000007 4 let A = A + [Int.min] 5 var ascend = [Int]() 6 var res = 0 7 for i in 0..<A.count { 8 while !ascend.isEmpty && A[ascend.last!] > A[i] { 9 let k = ascend.popLast()! 10 let j = ascend.last ?? -1 11 res += A[k] * (i - k) * (k - j) 12 } 13 res = res % m 14 ascend.append(i) 15 } 16 return res 17 } 18 } 12108ms 1 class Solution { 2 func sumSubarrayMins(_ A: [Int]) -> Int { 3 if A.isEmpty { 4 return 0 5 } 6 7 let n = A.count, MOD = 1000000007 8 var s = [Int]() 9 // sum of subarray mins ending with A[i] 10 var dp = [Int](repeating: 0, count: n) 11 // 3 1 2 4 5 1 12 for i in 0..<n { 13 dp[i] = (dp[i] + A[i]) % MOD 14 if i == 0 { 15 continue 16 } 17 if A[i-1] < A[i] { 18 dp[i] = (dp[i] + dp[i-1]) % MOD 19 } else { 20 var j = i-1 21 while j >= 0 && A[j] > A[i] { 22 j -= 1 23 } 24 dp[i] = (dp[i] + A[i] * (i-j-1)) % MOD 25 if j >= 0 { 26 dp[i] = (dp[i] + dp[j]) % MOD 27 } 28 } 29 } 30 var res = 0 31 for sum in dp { 32 res = (res + sum) % MOD 33 } 34 return res 35 } 36 }
|
请发表评论