[LeetCode] Semi-Ordered Permutation

2717. Semi-Ordered Permutation

You are given a 0-indexed permutation of n integers nums.

A permutation is called semi-ordered if the first number equals 1 and the last number equals n. You can perform the below operation as many times as you want until you make nums a semi-ordered permutation:

  • Pick two adjacent elements in nums, then swap them.

Return the minimum number of operations to make nums a semi-ordered permutation.

A permutation is a sequence of integers from 1 to n of length n containing each number exactly once.

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
class Solution {
public:
int semiOrderedPermutation(vector<int>& nums) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != 1) continue;
while(i) {
swap(nums[i-1], nums[i]);
i -= 1;
res += 1;
}
break;
}
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != nums.size()) continue;
while(i != nums.size() - 1) {
swap(nums[i], nums[i+1]);
i += 1;
res += 1;
}
break;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/04/PS/LeetCode/semi-ordered-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.