[Swift]LeetCode327. 區間和的個數 | Count of Range Sum

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mbonlwmm-kb.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in numsbetween indices i and j (i ≤ j), inclusive.git

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.github

Example:算法

Input: nums = , lower = , upper = ,
Output: 3 
Explanation: The three ranges are : , ,  and their respective sums are: .[-2,5,-1]-22[0,0][2,2][0,2]-2, -1, 2

給定一個整數數組 nums,返回區間和在 [lower, upper] 之間的個數,包含 lower 和 upper
區間和 S(i, j) 表示在 nums 中,位置從 i 到 j 的元素之和,包含 i 和 j (i ≤ j)。數組

說明:
最直觀的算法複雜度是 O(n2) ,請在此基礎上優化你的算法。微信

示例:優化

輸入: nums = , lower = , upper = ,
輸出: 3 
解釋: 3個區間分別是: , , 它們表示的和分別爲: [-2,5,-1]-22[0,0][2,2][0,2],-2, -1, 2。

140 ms
 1 class Solution {
 2     func countRangeSum(_ nums: [Int], _ lower: Int, _ upper: Int) -> Int {
 3         let count = nums.count
 4         if count == 0 {
 5             return 0
 6         }
 7         var sums = Array(repeating: 0, count: count+1)
 8         
 9         for i in 1..<count+1 {
10             sums[i] = sums[i-1] + nums[i-1]
11         }
12         
13         let maxSum = sums.max()!
14         
15         func mergeSort(_ low : Int, _ high : Int) -> Int {
16             if low == high {
17                 return 0
18             }
19             let mid = (low + high) >> 1
20             var res = mergeSort(low, mid) + mergeSort(mid+1, high)
21             var x = low, y = low
22             for i in mid+1..<high+1 {
23                 while x <= mid && sums[i] - sums[x] >= lower {
24                     x += 1
25                 }
26                 while y<=mid && sums[i] - sums[y] > upper {
27                     y += 1
28                 }
29                 res += (x-y)
30             }
31             
32             let sli = Array(sums[low..<high+1])
33             
34             var l = low, h = mid + 1
35             
36             for i in low..<high+1 {
37                 x = l <= mid ? sli[l - low] : maxSum
38                 y = h <= high ? sli[h - low] : maxSum
39                 
40                 if x < y {
41                     l += 1
42                 }else {
43                     h += 1
44                 }
45                 sums[i] = min(x,y)
46             }
47             
48             return res
49         }
50         
51         return mergeSort(0, count)
52     }
53 }
相關文章
相關標籤/搜索