LeetCode刷题-长度最小的子数组

长度最小的子数组

LeetCode刷题-长度最小的子数组_第1张图片
暴力解法:通过遍历所有的子数组找到满足条件的最小子数组。

class Solution:
	def min(self,s,nums):
     		minLen = len(nums) + 1 
     		for i ,_in enumerate(nums):
     			sum_all = 0 
     			for j,tmp in enumerate(nums[i:]):
     				sum_all += tmp
     				if sum_all >=s:
     					minLen = min(minLen,j+1)
     		if minLen == len(nums)+1:
     				return 0 
     		return minLen

双指针解法:
两个指针start和end,初始化为0,end往后移动,对于和超过s的区间[start,end],将区间缩小至最小–,依次更新最小长度,然后再扩展区间:end++,

public int min(int s , int nums[]) {
  int start = 0 , end = 0 ;
  int size = nums.length ;
  int sum = 0 ;
  int res = Integer.MAX_VALUE;
  while(end < size) {
   sum += nums[end] ;
   while(sum >=s) {
    res =res<(end-start + 1 )?res:(end -start +1) ;
    sum -=nums[start++];
   }
   end++ ;
  }
  if(res ==Integer.MAX_VALUE) return 0 ;
  return res ;
 }

你可能感兴趣的:(LeetCode,leetcode,java,动态规划,数组,双指针)