일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- DWG
- LeetCode
- 시바견
- shiba
- Decorator
- Python Code
- 밴픽
- Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- 109. Convert Sorted List to Binary Search Tree
- t1
- 43. Multiply Strings
- 컴퓨터의 구조
- iterator
- Generator
- Python
- attribute
- Python Implementation
- kaggle
- 프로그래머스
- 운영체제
- concurrency
- 파이썬
- 715. Range Module
- Regular Expression
- Protocol
- Convert Sorted List to Binary Search Tree
- data science
- Class
- 30. Substring with Concatenation of All Words
Archives
- Today
- Total
Scribbling
[LeetCode] 2340. Minimum Adjacent Swaps to Make a Valid Array 본문
Computer Science/Algorithms & Data Structures
[LeetCode] 2340. Minimum Adjacent Swaps to Make a Valid Array
focalpoint 2024. 7. 2. 16:19https://leetcode.com/problems/minimum-adjacent-swaps-to-make-a-valid-array/description/
1. Python
class Solution:
def minimumSwaps(self, nums: List[int]) -> int:
if len(nums) <= 1:
return 0
minVal = min(nums)
maxVal = max(nums)
for i in range(len(nums)):
if nums[i] == minVal:
minIdx = i
break
for i in range(len(nums)-1, -1, -1):
if nums[i] == maxVal:
maxIdx = i
break
if minIdx == maxIdx:
return 0
elif minIdx < maxIdx:
return minIdx + len(nums) - maxIdx - 1
else:
return minIdx + len(nums) - maxIdx - 2
2. C++
class Solution {
public:
int minimumSwaps(vector<int>& nums) {
if (nums.size() <= 1) return 0;
int minVal = *min_element(nums.begin(), nums.end());
int maxVal = *max_element(nums.begin(), nums.end());
int minIdx, maxIdx;
for (int i=0; i<nums.size(); i++) {
if (nums[i] == minVal) {
minIdx = i;
break;
}
}
for (int i=nums.size()-1; i>=0; i--) {
if (nums[i] == maxVal) {
maxIdx = i;
break;
}
}
if (minIdx == maxIdx) return 0;
else if (minIdx < maxIdx) return minIdx + nums.size() - maxIdx - 1;
else return minIdx + nums.size() - maxIdx - 2;
}
};
'Computer Science > Algorithms & Data Structures' 카테고리의 다른 글
[LeetCode] 2781. Length of the Longest Valid Substring (0) | 2024.07.10 |
---|---|
[Programmers] 방의 개수 (0) | 2024.07.02 |
[Programmers] 순위 (0) | 2024.06.28 |
[Programmers] 가장 먼 노드 (0) | 2024.06.28 |
[Programmers] 입국심사 (0) | 2024.06.27 |