最小交换以使C ++中的序列增加
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minSwap(vector<int>& A, vector<int>& B) {
int n = A.size();
vector <int> swapCnt(n), noSwapCnt(n);
swapCnt[0] = 1;
noSwapCnt[0] = 0;
for(int i = 1; i < n; i++){
swapCnt[i] = n;
noSwapCnt[i] = n;
if(A[i] > A[i - 1] && B[i] > B[i - 1]){
noSwapCnt[i] = noSwapCnt[i - 1];
swapCnt[i] = swapCnt[i - 1] + 1;
}
if(A[i] > B[i - 1] && B[i] > A[i - 1]){
swapCnt[i] = min(swapCnt[i], 1 + noSwapCnt[i - 1]);
noSwapCnt[i] = min(swapCnt[i - 1], noSwapCnt[i]);
}
}
return min(swapCnt[n - 1], noSwapCnt[n - 1]);
}
};
main(){
vector<int> v1 = {1,3,5,4};
vector<int> v2 = {1,2,3,7};
Solution ob;
cout << (ob.minSwap(v1, v2));
}输入值
[1,3,5,4] [1,2,3,7]
输出结果
1