[Swift]LeetCode325. 最大子數組之和爲k $ Maximum Size Subarray Sum Equals k

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

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.git

Example 1:github

Given nums = [1, -1, 5, -2, 3]k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)數組

Example 2:微信

Given nums = [-2, -1, 2, 1]k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)測試

Follow Up:
Can you do it in O(n) time?spa


給定一個數組nums和一個目標值k,找到一個子數組的最大長度總和爲k。若是沒有,則返回0。code

例1:htm

給定 nums = [1, -1, 5, -2, 3]k = 3,blog

返回4。(由於子數組[1,-1,5,-2]和爲3,是最長的)

例2:

給定 nums = [-2, -1, 2, 1]k = 1,

返回2。(由於子數組[-1,2]和爲1,是最長的)

跟進:

你能在O(N)時間內完成嗎?


Solution:

 1 class Solution {
 2     func maxSubArrayLen(_ nums:inout [Int],_ k:Int) -> Int {
 3         var sum:Int = 0
 4         var res:Int = 0
 5         var m:[Int:Int] = [Int:Int]()
 6         for i in 0..<nums.count
 7         {
 8             sum += nums[i]
 9             if sum == k
10             {
11                 res = i + 1
12             }
13             else if m[sum - k] != nil
14             {
15                 res = max(res, i - m[sum - k,default:0])
16             }
17             if m[sum] == nil
18             {
19                 m[sum] = i
20             }
21         }
22         return res        
23     }
24 }

點擊:Playground測試

1 let k1:Int = 3
2 var nums1:[Int] = [1, -1, 5, -2, 3]
3 print(Solution().maxSubArrayLen(&nums1,k1))
4 //Print 4
5 
6 let k2:Int = 1
7 var nums2:[Int] = [-2, -1, 2, 1]
8 print(Solution().maxSubArrayLen(&nums2,k2))
9 //Print 2
相關文章
相關標籤/搜索