获取长度最小的子数组

给定一个整数数组和一个整数key,如果子数组元素之和不小于key,返回该类子数组中长度最小子数组对应的

此题有两类解法:

1)暴力解法(使用两重for循环),代码如下所示

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int getMinLength(vector<int>& arr, int key) {
    int minLength = arr.size();
    for(int i = 0; i < arr.size(); i++) {
        int sum = 0;
        for(int j = i; j < arr.size(); j++) {
            sum += arr[j];
            if(sum >= key) {
                int length = j - i + 1;
                if(length == 1) {
                    return 1;
                }
                if(length < minLength) {
                    minLength = length;
                }
            }
        }
    }

    return minLength;
}

int main() {
    vector<int> arr;
    string line;
    string temp;
    while (getline(cin, line)) {
        int i;
        for (i = 0; i < line.size(); i++) {
            if(line[i] == '[') {
                continue;
            }
            if(line[i] == ',') {
                arr.emplace_back(stoi(temp));
                temp.clear();
                continue;
            }
            if(line[i] == ']') {
                arr.emplace_back(stoi(temp));
                temp.clear();
                break;
            }
            temp += line[i];
        }
        int key = stoi(line.substr(i + 2));

        int len = getMinLength(arr, key);
        cout << len << endl;
        arr.clear();
    }

    return 0;
}

算法的时间复杂度:O(n^2)

算法的空间复杂度:O(1)

2)滑动窗口法

类似于双指针法,慢指针指向子数组的头部,快指针指向子数组的尾部,当子数组之和大于key时,更新符合条件的子数组的最小长度,慢指针向后移动,当子数组之和小于key时,快指针向后移动,代码如下所示

int getMinLength(vector<int>& arr, int key) {
    int minLength = arr.size();
    int sum = 0;
    int slowIndex = 0;
    int fastIndex = 0;

    sum += arr[fastIndex];

    while(true) {
        while(sum >= key) {
            int length = fastIndex - slowIndex + 1;
            if(length == 1) {
                return 1;
            }
            if(length < minLength) {
                minLength = length;
            }
            sum -= arr[slowIndex];
            slowIndex++;
        }
        fastIndex++;
        if(fastIndex < arr.size()) {
            sum += arr[fastIndex];
        }
        else {
            break;
        }
    }

    return minLength;
}

算法的时间复杂度:O(n)

算法的空间复杂度:O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值