![](/img/trans.png)
[英]How can I find the minimum number of swaps in a consecutive unordered array (vector)?
[英]Minimum Swaps 2 - minimum number of swaps required to sort a vector in ascending order
我正在做一個相當簡單的 HackerRank 測試,它要求用戶編寫一個函數,該函數返回按升序對無序向量進行排序所需的最小交換次數,例如
開始: 1, 2, 5, 4, 3
結束: 1, 2, 3, 4, 5
最小交換次數:1
我編寫了一個適用於 13/14 測試用例的函數,但對於最后一個用例來說太慢了。
#include<iostream>
#include<vector>
using namespace std;
int mimumumSwaps(vector<int> arr) {
int p = 0; // Represents the (index + 1) of arr, e.g. 1, 2, ..., arr.size() + 1
int swaps = 0;
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i) {
p++;
if (*i == p) // Element is in the correct place
continue;
else{ // Iterate through the rest of arr until the correct element is found
for (vector<int>::iterator j = arr.begin() + p - 1; j != arr.end(); ++j) {
if (*j == p) {
// Swap the elements
double temp = *j;
*j = *i;
*i = temp;
swaps++;
break;
}
}
}
}
return swaps;
}
int main()
{
vector<int> arr = { 1, 2, 5, 4, 3 };
cout << mimumumSwaps(arr);
}
我將如何進一步加快速度?
是否有任何我可以導入的功能可以為我加快流程?
有沒有辦法做到這一點,而無需實際交換任何元素並簡單地計算出最小值。 我想象的交換會加快處理時間?
所有排列都可以分解為循環子集。 找到所說的子集。
將 K 個元素的子集旋轉 1 次需要 K-1 次交換。
遍歷數組,直到找到不合適的元素。 走那個循環直到它完成。 前進,跳過您已經放入循環的元素。 每個周期的總和(大小為 1)。
要跳過,請維護一組有序或無序的未檢查項目,並在檢查它們時快速刪除。
我認為這給出了 O(n lg n) 左右的最佳交換計數。
#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
using namespace std;
int minimumSwaps(vector<int> arr)
{
int i,c,j,k,l;
j=c=0;
l=k=arr.size();
while (j<k)
{
i=0;
while (i<l)
{
if (arr[i]!=i+1)
{
swap(arr[i],arr[arr[i]-1]);
c++;
}
i++;
}
k=k/2;
j++;
}
return c;
}
int main()
{
int n,q;
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++)
{
cin>>q;
arr.push_back(q);
}
int res = minimumSwaps(arr);
cout << res << "\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.