[Swift]LeetCode325. 最大子数组之和为k $ Maximum Size Subarray Sum Equals k
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10706864.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.
Example 1:
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?
给定一个数组nums和一个目标值k,找到一个子数组的最大长度总和为k。如果没有,则返回0。
例1:
给定 nums = [1, -1, 5, -2, 3]
, k = 3
,
返回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