I am getting segmentation fault. Can you help me with this?
I am getting segmentation fault. Can you help me with this?
- Create the map by filling the number as the key and the index at which it is present as the value
- Iterate over the whole array.
- For element at a particular index m we will check if it is present at its best spot or not.
- The best spot of any number num is the N-num index of the array.
- If the number is not present at its best spot then we will swap the number with element present at that spot.
- As we have stored the index of every element in the map we can easily retrieve that from the map to get the swap done.
refer this -->
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,k;
cin >> n >> k;
vector<int> v;
unordered_map<int,int> m ;
for(int i=0;i<n;i++){
int x;
cin >> x;
v.push_back(x);
m[v[i]] = i ;
}
for(int i=0;i<n && k>0;i++){
int x = n - i;
if(v[i] == x){
//Already correct element
continue;
}
int index = m[x];
m[v[i]] = index ;
m[x] = i;
swap(v[i],v[index]);
k--;
}
for(int i=0;i<n;i++){
cout << v[i] << " ";
}
return 0;
}
Got it thanks! You can resolve it now.
1 Like
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.