[LeetCode] Minimum Distance to the Target Element

아르당·2026년 7월 9일

LeetCode

목록 보기
396/571
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수 배열 nums(0부터 시작)와 2개의 정수 target과 start가 주어졌을 때, nums[i] == target이고 abs(i - start)가 최소가 되는 인덱스 i를 찾아라. abs(x)는 x의 절대값이다.
abs(i - start)를 반환해라.
target이 nums에 존재함이 보장된다.

Example

#1
Input: nums = [1, 2, 3, 4, 5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5만 target과 같은 값이라서 답은 abs(4 - 3) = 1이다.

#2
Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1만 target과 같은 값이라서 답은 abs(0 - 0) = 0이다.

#3
Input: nums = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], target = 1, start = 0
Output: 0
Explanation: nums의 모든 값은 1이지만, nums[0]의 최소값은 abs(i - start)인 abs(0 - 0) = 0이다.

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^4
  • 0 <= start < nums.length
  • target은 nums안에 있다.

Solved

class Solution {
    public int getMinDistance(int[] nums, int target, int start) {
        int min = Integer.MAX_VALUE;

        for(int i = 0; i < nums.length; i++){
            if(nums[i] == target){
                min = Math.min(min, Math.abs(start - i));
            }
        }

        return min;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글