当前位置: 首页> 教育> 锐评 > 【数组】- 长度最小的子数组

【数组】- 长度最小的子数组

时间:2025/7/12 5:49:06来源:https://blog.csdn.net/m0_72560900/article/details/140002581 浏览次数:0次

1. 对应力扣题目连接

  • 长度最小的子数组

2. 实现案例代码


public class SubarrayWithTheSmallestLength {public static void main(String[] args) {int[] nums = new int[]{1, 2, 3, 4, 5};int target = 8;List<Integer> targetArray = new ArrayList();// 调用方法查询最小子数组int result = minSubArrayLen(target, nums,targetArray);System.out.println("最小子数组的长度为:" + result);System.out.println(targetArray);}/*** 求出最小子数组的长度,并获取最小子数组* @param target 目标和* @param nums 数组* @param targetArray 满足条件的最小子数组* @return 最小子数组的长度*/public static int minSubArrayLen(int target, int[] nums, List<Integer> targetArray) {int n = nums.length;int minLength = Integer.MAX_VALUE;int sum = 0;int left = 0;for (int right = 0; right < n; right++) {sum += nums[right];minLength = Math.min(minLength, right - left + 1);while (sum >= target) {if (right - left + 1 < minLength) {minLength = right - left + 1;targetArray.clear();for (int i = left; i <= right; i++) {targetArray.add(nums[i]);}}sum -= nums[left++];}}return minLength == Integer.MAX_VALUE ? 0 : minLength;}
}
关键字:【数组】- 长度最小的子数组

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: