209. 长度最小的子数组
题目大意:
给定一个数组以及一个target,找到其中长度最小,并且数组和大于等于target的子数组。
思路:
暴力的解法很容易,但是用滑动数组时间复杂可以直接降为 O(n)。
题解:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int low = 0, high = 0;
int length = nums.size();
int count = 0x3fffff;
int sum = 0;
for(high = 0; high < length; ++high)
{
sum += nums[high];
while(sum >= target)
{
if( high - low + 1 < count)
count = high - low + 1;
sum -= nums[low];
++low;
}
}
if(count == 0x3fffff)
count = 0;
return count;
}
};
904. 水果成篮
题目大意:
直接都题目,读完之后还有点懵,但是看了测试用例之后就明白了,题意就是找 只包含两个不同元素的最大子数组。
思路:
类似于209,209的条件是窗口内的数总和 >= target
这一题是要求窗口内的不同数字的个数为2
题解:
/*------------------------
类似于209,209的条件是窗口内的数总和 >= target
这一题是要求窗口内的不同数字的个数为2
---------------------------*/
class Solution {
public:
int totalFruit(vector<int>& tree) {
map<int, int> fruits;
int low = 0, high = 0;
int length = tree.size();
int count = 0;
for(high = 0; high < length; ++high)
{
++fruits[tree[high]];
if(fruits.size() <= 2)
/*这里写小于等于2 是应对 [1,1,1,1,1,1,1,1,1] 这种情况 */
{
if(high-low+1 > count)
count = high - low + 1;
}
while(fruits.size() > 2)
{
if(fruits[tree[low]] == 1)
{
map<int,int> ::iterator iter = fruits.find(tree[low]);
fruits.erase(iter);
}
else
{
--fruits[tree[low]];
}
++low;
}
}
return count;
}
};
待做:
904、76