forked from PhysicsX/ExampleCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimumSwap.cpp
More file actions
68 lines (45 loc) · 1.56 KB
/
minimumSwap.cpp
File metadata and controls
68 lines (45 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <vector>
#include <algorithm>
// minimum swap for descending order.
class Solution
{
public:
int minimumSwapToSort(std::vector<int>& vec)
{
int result = 0;
int size = vec.size();
std::pair<int,int> pos[size];
for(int i = 0; i<size; i++)
{
pos[i].first = vec[i];
pos[i].second = i;
}
std::sort(pos, pos+size,
[](const std::pair<int,int> &p1, const std::pair<int,int> &p2){
return (p1.first > p2.first);
});
std::vector<int> visited(size, false);
for(int i=0; i<size; i++)
{
if(visited[i] || pos[i].second == i)
continue;
int cycleSize = 0;
int j = i;
while(!visited[j])
{
visited[j] = true;
j = pos[j].second;
cycleSize++;
}
if(cycleSize > 0)
result += (cycleSize -1);
}
return result;
}
};
int main()
{
std::vector<int> vec {1,5,4,3,2,1};
std::cout<<Solution().minimumSwapToSort(vec);
}