You are given a 0-indexed integer array nums.
Swaps of adjacent elements are able to be performed on nums.
A valid array meets the following conditions:
- The largest element (any of the largest elements if there are multiple) is at the rightmost position in the array.
- The smallest element (any of the smallest elements if there are multiple) is at the leftmost position in the array.
Return the minimum swaps required to make nums a valid array.
Example 1:
Input: nums = [3,4,5,5,3,1]
Output: 6
Explanation: Perform the following swaps:
- Swap 1: Swap the 3rd and 4th elements, nums is then [3,4,5,3,5,1].
- Swap 2: Swap the 4th and 5th elements, nums is then [3,4,5,3,1,5].
- Swap 3: Swap the 3rd and 4th elements, nums is then [3,4,5,1,3,5].
- Swap 4: Swap the 2nd and 3rd elements, nums is then [3,4,1,5,3,5].
- Swap 5: Swap the 1st and 2nd elements, nums is then [3,1,4,5,3,5].
- Swap 6: Swap the 0th and 1st elements, nums is then [1,3,4,5,3,5].
It can be shown that 6 swaps is the minimum swaps required to make a valid array.
Example 2:
Input: nums = [9]
Output: 0
Explanation: The array is already valid, so we return 0.
Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 105
class Solution:
def minimumSwaps(self, nums: List[int]) -> int:
if len(nums)==1:
return 0
cmax=[-1,-1]
cmin=[float("inf"),-1]
for i in range(len(nums)):
if nums[i]>=cmax[0]:
cmax=[nums[i],i]
if nums[i]<cmin[0]:
cmin=[nums[i],i]
ans=len(nums)-cmax[1]+cmin[1]-1
if cmax[1]>cmin[1]:
return ans
else:
return ans-1
'알고리즘 문제 > Leetcode' 카테고리의 다른 글
1910. Remove All Occurrences of a Substring (0) | 2023.05.02 |
---|---|
419. Battleships in a Board (0) | 2023.05.02 |
1973. Count Nodes Equal to Sum of Descendants (0) | 2023.05.02 |
811. Subdomain Visit Count (0) | 2023.05.02 |
1602. Find Nearest Right Node in Binary Tree (0) | 2023.05.02 |