其实,这道题不难,理解题意也不用很长时间。
本来的思路是想通过构造一个反向数组用来判断插入的最小次数,结果部分答案 算出来的始终比 正确结果 多了 1。
才发现,那个思路有个很大的bug;
再后来改用双循环找0判断法,答案对是对了,但是一个超级长的用例 超时了;
再后来,尝试各种剪枝,降低时间复杂度,但是就是无论怎么降,双循环就是没办法;
最后,突然想起来 用滑动窗口去解决!!!!就维护窗口尾部和上一个窗口的头部信息就好!!!
好吧,虽然不难,确实花了我很长时间去改 ,o(╥﹏╥)o
代码:
class Solution {
public:
int flag=0;
int count_1=0;
int minSwaps(vector<int>& chess) {
int n=chess.size();
if(n<=1)return flag;
for(int i=0;i<n;i++){
if(chess[i]==0)
continue;
else
count_1++;
}
if(count_1<=1)return flag;
int ans=INT_MAX;
int temp1=0;
int index=0;
for(int i=0;i<count_1;i++)
{if(chess[i]==0)temp1++;}
ans=ans>temp1?temp1:ans;
for(int left=index+1,right=left+count_1-1;left<=n-count_1;){
if(chess[index]==0&&chess[right]==1)temp1--;
else if(chess[index]==1&&chess[right]==0)temp1++;
else temp1=temp1;
ans=ans>temp1?temp1:ans;
index=left;
left++;
right++;
}
return ans;
}
};
当时没做出来,我是真的菜啊啊啊啊啊。