美文网首页
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

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