Leetcode 209. 长度最小的子数组 c#

给定一个含有 n 个正整数的数组和一个正整数 target 。

找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

示例 1:

输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:

输入:target = 4, nums = [1,4,4]
输出:1
示例 3:

输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0

思路就是从数组第一位开始判断是否大于target,不大于就与后一位相加,一直加到大于target,记录加了几位,依次循环,第一次从第一位开始往后加,第二次从第二位开始往后加,找到加的次数最少的返回。
 public int MinSubArrayLen(int target, int[] nums) {
   int a = 0;
            int res = 0;
            int s = 0;
            int sum = 0;
            int x = 0;
            List<int> lis = new List<int>();
            if (nums.Max() >= target) return 1;
            for (int i = 0; i < nums.Length; i++)
            {
                sum += nums[i];
            }
            if (sum < target) return 0;
            if (sum == target) return nums.Length;
            for (int j = 0; j < nums.Length; j++)
            {
               
                for (int i = s; i < nums.Length; i++)
                {

                    x = x+1;
                    if (a < target)
                    {
                        a += nums[i];
                        if (a >= target)
                        {
                            res = x;
                            
                        }
                        else
                        {
                            res = nums.Length;
                        }

                    }
                    else
                    {
                        if (a >= target)
                        {
                            break;

                        }
                        else
                        {
                            res = nums.Length;
                        }
                       
                    }
                }
                lis.Add(res);
                s++;
                a = 0;
                res = 0;
                x = 0;

            }
            return lis.Min();
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值