一、209长度最小的子数组
1.题目
https://leetcode-cn.com/problems/minimum-size-subarray-sum/
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
2.思路
思路如下代码
注意:内层循环要用while,用if判断的话,sum >= target情况下,再次判断的sum值会多加一个nums[right]
3.代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int minCount = Integer.MAX_VALUE;
int left = 0;
int right = 0;
int n = nums.length-1;
while (right <= n && left<=n){
sum += nums[right];
while(sum >= target){
minCount = Math.min(minCount,right-left+1);
sum -= nums[left];
left++;
}
right++;
}
return minCount==Integer.MAX_VALUE?0:minCount;
}
}
二、1456. 定长子串中元音的最大数目
1.题目
https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/submissions/
给你字符串 s 和整数 k 。
请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。
英文中的 元音字母 为(a, e, i, o, u)。
2.思路
分两步滑动窗口遍历s:
1.记录0-k-1区间的元音字母个数;
2.k-n区间,判断新进入区间的数字是否为元音,并减去从区间中去掉的数字
3.代码
class Solution {
public int maxVowels(String s, int k) {
int count = 0;
int n =s.length()-1;
for (int i = 0;i<k;i++){
//if (isValue(s.charAt(i))==1){
// count++;
//}
count += isValue(s.charAt(i));
}
int res = count;
for (int j =k; j<=n;j++){
count = count+ isValue(s.charAt(j))-isValue(s.charAt(j-k));
res = Math.max(count, res);
}
return res;
}
public int isValue(char c){
if (c=='a' || c=='e'||c=='i'||c=='o'||c=='u' ){
return 1;
}else{
return 0;
}
}
}