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 |
Tags
- string
- two pointers
- Binary Tree
- database
- 구현
- geometry
- Number Theory
- Class
- 자바
- SQL
- Binary Search
- hash table
- sorting
- Method
- Stack
- implement
- 코딩테스트
- java
- 파이썬
- Tree
- 코테
- Math
- Data Structure
- simulation
- Counting
- bit manipulation
- dynamic programming
- Matrix
- array
- greedy
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 2515. Shortest Distance to Target String in a Circular Array 본문
코딩테스트 풀이/JAVA
[LeetCode/Easy] 2515. Shortest Distance to Target String in a Circular Array
무지맘 2023. 5. 6. 01:111. Input
1) String[] words
2) String target
3) int startIndex
2. Output
1) startIndex부터 target까지의 떨어진 거리를 계산해서 가장 짧은 거리를 반환
- 떨어진 거리는 왼쪽, 오른쪽 양 방향으로 계산 가능하다.
2) target이 words에 없다면 -1을 반환
3. Constraint
1) 1 <= words.length <= 100
2) 1 <= words[i].length <= 100
3) words의 요소들과 target은 영어 소문자로만 이루어져 있다.
4) 0 <= startIndex < words.length
4. Example
Input: words = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1 -> Output: 1
설명: target은 0번과 4번에 있다.
- 1번에서 0번까지 가려면 오른쪽으로 4번 또는 왼쪽으로 1번 가면 된다.
- 1번에서 4번까지 가려면 오른쪽으로 3번 또는 왼쪽으로 2번 가면 된다.
- 가장 짧은 거리는 1이므로 1을 반환한다.
5. Code
1) 첫 코드(2023/05/06)
class Solution {
public int closetTarget(String[] words, String target, int startIndex) {
int n = words.length, min = Integer.MAX_VALUE;
for(int i=0 ; i<words.length ; i++){
if(words[i].equals(target)){
if(i==startIndex){
min = 0; break;
}
int d;
if(startIndex<=i)
d = Math.min(i-startIndex, n-i+startIndex);
else
d = Math.min(startIndex-i, n-startIndex+i);
min = Math.min(min, d);
}
}
return min==Integer.MAX_VALUE ? -1 : min;
}
}
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 2540. Minimum Common Value (0) | 2023.05.06 |
---|---|
[LeetCode/Easy] 2520. Count the Digits That Divide a Number (0) | 2023.05.06 |
[LeetCode/Easy] 2511. Maximum Enemy Forts That Can Be Captured (0) | 2023.05.06 |
[LeetCode/Easy] 2506. Count Pairs Of Similar Strings (0) | 2023.05.06 |
[LeetCode/Easy] 2500. Delete Greatest Value in Each Row (0) | 2023.05.05 |