一、1052. Grumpy Bookstore Owner
解题思路:
1、求固定大小的最大连续子序列
把题目转换为求一个序列的固定长度的最大连续子序列去做。在该子序列内所有custommers都是满意的,在该子序列外customers是否满意取决于对应位置的grumpy的值。
利用前缀和实现对连续子序列的和的O(1)求解
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
int ans=0,maxval=0,maxleft=0,i=0,n=grumpy.size();
vector<int> v(n+1,0);//customers的前缀和数组
for(int i=0;i<n;++i)
v[i+1]=customers[i]*grumpy[i];
for(int i=1;i<=n;++i)
v[i]+=v[i-1];
for(int left=0;left+X<=n;++left)
{
if(maxval<v[left+X]-v[left])
{
maxval=v[left+X]-v[left];
maxleft=left;
}
}
//将customers分为在最大子序列内和在最大子序列外
while(i<n)
{
if(maxleft<=i&&i<maxleft+X)
ans+=customers[i];
else
ans+=customers[i]*(!grumpy[i]);
++i;
}
return ans;
}
};
2、滑动窗口
求最大或者最小的固定长度的连续子序列的和可以使用滑动窗口这种方法来实现。即使用一个指向窗口左边的标志和一个指向窗口右边的标志,先固定左标志,移动右标志,当窗口的长度为指定的长度时则得到了一个固定长度的连续子序列的和。此后通过控制左标志和右标志,使最后计算序列和的时候窗口大小总是为指定的大小。
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
int n=grumpy.size();
int ans=0,maxX=0,sum=0;
//将计算过的customers的值置为0防止重复计算
for(int i=0;i<n;++i)
ans+=customers[i]*(!grumpy[i]),customers[i]*=grumpy[i];
for(int left=0,right=0;right<n;++right)
{
maxX+=customers[right];
if(right-left+1==X)
sum=max(sum,maxX),maxX-=customers[left++];
}
return ans+sum;
}
};
二、1053. Previous Permutation With One Swap
这一题在contest期间测试样例出错了,所以题目评价不好,现在测试样例已经改正,个人觉得改正后还是不算水的题。
这一题用O(n)的复杂度就可以解。
要求只交换两个数来求得比当前排列小的所有排列中最大的那个排列。首先要清楚若A[i]<=A[j],i<j,则A[i]和A[j]必不可交换。其次为满足要求(最大的那个排列),A[i]必须与在其右边的所有小于它的数中最大的一个交换,而且如果这样的数有多个,为了保证得到的是最大的排列,则A[i]要与这样的数中最左边的那个交换。
class Solution {
public:
vector<int> prevPermOpt1(vector<int>& A) {
int n=A.size();
int left=n-2,right=n-1;
while(left>=0&&A[left]<=A[left+1])
--left;
if(left<0) //left<0则当前排列已经是最小的
return A;
while(A[left]<=A[right])
--right;
while(A[right]==A[right-1])
--right;
swap(A[left],A[right]);
return A;
}
};
三、1054. Distant Barcodes
做这个题让我深刻记住了原来pair也可以作为优先队列的元素,且pair的默认比较方式是先比较first再比较second。
题目保证必存在解。出现次数最多的那个数最好是每隔一位出现一次,以此保证最后不会出现两个一样的数相邻。根据这一想法,采用优先队列。
class Solution {
public:
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
//计数
vector<int> cnt(10001,0);
for(int b:barcodes)
++cnt[b];
priority_queue<pair<int,int>> q;
//pair.first=频数 是为了每次得到当前剩余个数最多的那个数
for(int i=1;i<10001;++i)
if(cnt[i])
q.push({cnt[i],i});
vector<int> ans;
while(q.size()>=2)
{
auto a=q.top();q.pop();
auto b=q.top();q.pop();
ans.push_back(a.second);
ans.push_back(b.second);
if(a.first>1)
q.push({a.first-1,a.second});
if(b.first>1)
q.push({b.first-1,b.second});
}
if(!q.empty())
ans.push_back(q.top().second);
return ans;
}
};