算法-长度最小的子数组
下面的算法是跟着【代码随想录】学习的,数据结构是数据,算法是移除元素,这些是我的解法,如果有什么想法,欢迎大家留言与我讨论,谢谢。
1,LeetCode209
给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度 。 如果不存在符合条件的子数组,返回 0 。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int minLen = Integer.MAX_VALUE;
int sum = 0;
int index = 0;
for(int i = 0;i < nums.length;i++){
sum += nums[i];
while(sum >= target){
minLen = Math.min(minLen,i - index + 1);
sum -= nums[index++];
}
}
return minLen == Integer.MAX_VALUE ? 0: minLen;
}
}
2,LeetCode904
你正在探访一家农场,农场从左到右种植了一排果树。这些树用一个整数数组 fruits 表示,其中 fruits[i] 是第 i 棵树上的水果 种类 。
你想要尽可能多地收集水果。然而,农场的主人设定了一些严格的规矩,你必须按照要求采摘水果:
- 你只有 两个 篮子,并且每个篮子只能装 单一类型 的水果。每个篮子能够装的水果总量没有限制。
- 你可以选择任意一棵树开始采摘,你必须从 每棵 树(包括开始采摘的树)上 恰好摘一个水果 。采摘的水果应当符合篮子中的水果类型。每采摘一次,你将会向右移动到下一棵树,并继续采摘。
- 一旦你走到某棵树前,但水果不符合篮子的水果类型,那么就必须停止采摘。
给你一个整数数组 fruits ,返回你可以收集的水果的 最大 数目。
class Solution {
public int totalFruit(int[] fruits) {
List<Integer> list = new ArrayList();
// 用于记录数量
int count1 = 0;
// 用来记录种类
int count2 = 0;
int maxCount = 0;
for (int i = 0; i < fruits.length; i++) {
if (list.contains(fruits[i])) {
list.add(fruits[i]);
count1++;
maxCount = Math.max(maxCount, count1);
} else {
if (count2 < 2) {
list.add(fruits[i]);
count1++;
count2++;
maxCount = Math.max(maxCount, count1);
} else {
while (count2 != 1) {
Integer temp = list.get(0);
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
Integer next = it.next();
if (next.equals(temp)) {
it.remove();
count1--;
} else {
break;
}
}
if (!list.contains(temp)) {
count2--;
}
}
list.add(fruits[i]);
count1++;
maxCount = Math.max(maxCount, count1);
count2++;
}
}
}
return maxCount;
}
}
3,LeetCode76
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
目前还没有写出来