美文网首页
16.LeetCode刷题For Swift·209. Mini

16.LeetCode刷题For Swift·209. Mini

作者: 富城 | 来源:发表于2021-01-06 09:15 被阅读0次

1、原题

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

2、思路

3、代码

class Solution {
    func minSubArrayLen(_ s: Int, _ nums: [Int]) -> Int {
        // 结果,初始化为一个超大值,不能为空
        var result = INTPTR_MAX
        // 左指针
        var i = 0
        // 求和
        var sum = 0
        // 最小长度
        var subLength = 0
        for j in 0..<nums.count {
            // 求和,判断和是否大于等于s
            sum += nums[j]
            while sum >= s {
                // 小数组的长度
                subLength = j - i + 1
                result = result < subLength ? result : subLength
                // 然后还得减去小数组的第一个元素
                sum -= nums[i]
                i += 1
            }
        }
        return result == INTPTR_MAX ? 0 : result
    }
}

相关文章

  • 16.LeetCode刷题For Swift·209. Mini

    1、原题 Given an array of n positive integers and a positive...

  • 10.LeetCode刷题For Swift·209. 长度最小

    1、原题 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子...

  • leedcode刷题swift

    /**给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回...

  • 刷题Leetcode - swift

    难度系数: 简单:✨ 中等:✨✨ 困难:✨✨✨ 1、两数之和 ✨ 给定一个整数数组 nums 和一个目标值 tar...

  • Swift 算法刷题

    目标一周刷2道题也不知道能坚持几天,这玩意在leetcode做完怎么保存啊 给一个有序的数组,数组中有重复数字,输...

  • LeetCode 数组专题 5:双索引技术之二:滑动窗口

    例题1:LeetCode 第 209 题:长度最小的子数组 传送门:英文网址:209. Minimum Size ...

  • 刷题刷题

    时间紧迫,任务繁重,又有疫情影响,搞的人心惶惶,一时间复习得不安宁,又舍不得摆烂。 在焦灼、惶恐的情绪中,紧张急迫...

  • Swift-从字符串匹配看普通算法与KMP算法

    最近在leetcode上刷题,当然,是用swift,中间的辛酸经历就不提了,不得不说swift在便利性上的确十分强...

  • 2022-09-16

    刷题,刷题还是刷题

  • 2018-07-16

    刷题,祸害的何止是教育? 报班,刷题;买练习册,刷题;家教,刷题;跟不上,刷题;学得好,刷题;为了抢跑,刷题;为了...

网友评论

      本文标题:16.LeetCode刷题For Swift·209. Mini

      本文链接:https://www.haomeiwen.com/subject/pippoktx.html