每日算法(一) 求一个数组的所有连续的子数组

题目:求一个数组的所有连续的子数组


#include
using namespace std;
void getAllSubArray(int arr[], int n) {
	for(int i=1; i<=n; i++) {
		int j=0;
		j+=i;
		int p=0;
		while(j<=n) {
			printf("[");
			
			for(int k=p; k
类似的题目:

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.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

来自于LeetCode 209 Minimum Size Subarray Sum

中文的意思是:给定一个整数型数组和一个数字S,找到数组中最短的一个连续的子数组,使得连续子数组的数字和sum>=s,返回这个最短的连续子数组的返回值

解决思路:通过暴力解:遍历所有的连续的子数组

     计算其和sum,验证sum>=s

根据上面求一个数组所有连续子数组的算法,我们可以很简单的改成针对于此问题的算法,代码如下


class Solution {
public:
   int minSubArrayLen(int s, vector& nums) {
        int n = nums.size();
        for(int i=1; i<=n; i++) {
		int j=0;
		j+=i;
		int p=0;
		while(j<=n) {
			int num = 0;
			for(int k=p; k=s)
				return i;
			j++;
			p++;
		}
	}
	return 0;
}
};

虽然暴力法好想,但是常常伴随着时间效率低下的缺点,如果按照上面的代码进行提交,会提示时间超时的错误。

因此在这里再给大家分享一种解决类似问题的一种好的思路“滑块法” ,代码如下:


class Solution {
public:
   int minSubArrayLen(int s, vector& nums) {
       int size = nums.size();
       int r = -1, l = 0;
       int res = size + 1;
       int sum = 0;
       while(l < size) {
       	
       	if(sum < s && r + 1 < size){
       		 r++;
       		 sum += nums[r];
		}else {
			
			sum -= nums[l];
            l++;
		}
		if(sum >= s) {
			res = min(res, r-l+1);
		}
	   }
	   if(res == size + 1)
	   		return 0;
	   return res;
}
};


你可能感兴趣的:(C++,算法)