-
Notifications
You must be signed in to change notification settings - Fork 110
/
solution.java
54 lines (38 loc) · 1.1 KB
/
solution.java
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
import java.io.*;
import java.util.*;
public class solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int K = in.nextInt();
int[] n = new int[N];
Map<Integer, Integer> index = new HashMap<>();
for (int i = 0; i < N; i++) {
n[i] = in.nextInt();
index.put(n[i], i);
}
int max = N;
for (int j = 0; j < N; j++) {
int maxIndex = index.get(max);
// if the index isn't equal to j
if (maxIndex != j) {
// make a swap
K--;
int temp = n[j];
n[j] = max;
n[maxIndex] = temp;
// update indexes
index.put(max, j);
index.put(temp, maxIndex);
}
max--;
// break the loop if swaps are exhausted
if (K == 0) {
break;
}
}
for (int i = 0; i < N; i++) {
System.out.print(n[i] + " ");
}
}
}