Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Matrix
- hash table
- 구현
- bit manipulation
- Math
- Counting
- Data Structure
- implement
- dynamic programming
- Stack
- string
- geometry
- array
- greedy
- Tree
- Binary Search
- 코테
- java
- simulation
- Class
- 코딩테스트
- sorting
- Binary Tree
- database
- two pointers
- Number Theory
- 자바
- SQL
- Method
- 파이썬
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 2717. Semi-Ordered Permutation 본문
1. Input
1) int[] nums
- nums.length == n
- 1부터 n까지 무작위로 나열되어있는 배열
2. Output
1) 인접한 두 요소의 위치를 바꾸면서 맨 앞은 1이고 맨 뒤는 n인 배열을 만드는 데 필요한 최소 횟수를 반환
- 다른 요소들의 순서는 상관 없다.
3. Constraint
1) 2 <= n <= 50
2) 1 <= nums[i] <= 50
3) nums는 순열이다.
- 순열은 길이가 n이고 1부터 n까지의 수가 1번씩 나타나는 수열을 말한다.
4. Example
Input: nums = [2,1,4,3] -> Output: 2
Input: nums = [1,3,4,2,5] -> Output: 0
설명:
- 2와 1을 바꾸고, 4와 3을 바꾸면 [1,2,3,4]가 된다.
- 이미 맨 앞이 1, 맨 뒤가 5이므로 바꿀 필요가 없다.
5. Code
class Solution {
public int semiOrderedPermutation(int[] nums) {
int idx1 = -1, idxn = -1, i = 0, n = nums.length;
while(i<n && (idx1==-1 || idxn==-1)){
if(nums[i]==1) idx1 = i;
else if(nums[i]==n) idxn = i;
i++;
}
if(idx1==0){
if(idxn==n) return 0;
else return n-1-idxn;
} else{
if(idxn==n) return idx1;
else if(idx1<idxn) return n-1-idxn+idx1;
else return n-2-idxn+idx1;
}
}
}
- 100%, 44%
2) 조건문이 조잡해보여서 다시 써본 코드
class Solution {
public int semiOrderedPermutation(int[] nums) {
int idx1 = -1, idxn = -1, i = 0, n = nums.length;
while(i<n && (idx1==-1 || idxn==-1)){
if(nums[i]==1) idx1 = i;
else if(nums[i]==n) idxn = i;
i++;
}
if(idx1<idxn)
return idx1 + n-idxn-1;
else
return idx1 + n-idxn-2;
}
}
- 100%, 96%
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 2733. Neither Minimum nor Maximum (0) | 2023.06.30 |
---|---|
[LeetCode/Easy] 2729. Check if The Number is Fascinating (0) | 2023.06.30 |
[LeetCode/Easy] 2716. Minimize String Length (0) | 2023.06.30 |
[LeetCode/Easy] 2710. Remove Trailing Zeros From a String (0) | 2023.06.30 |
[LeetCode/Easy] 2706. Buy Two Chocolates (0) | 2023.06.30 |