,敢教日月换新天。为有牺牲多壮志

[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 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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
复制代码

 

posted @   为敢技术  阅读(332)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°