코린이의 소소한 공부노트

[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:11

1. Input

1) String[] words

2) String target

3) int startIndex

 

2. Output

1) startIndex부터 target까지의 떨어진 거리를 계산해서 가장 짧은 거리를 반환

- 떨어진 거리는 왼쪽, 오른쪽 양 방향으로 계산 가능하다.

2) targetwords에 없다면 -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

설명: target0번과 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;
    }
}