[LeetCode] Find All K-Distant Indices in an Array

아르당·2026년 8월 16일

LeetCode

목록 보기
468/563
post-thumbnail

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

Problem

인덱스가 0부터 시작하는 정수 배열 nums와 2개의 정수 key와 k가 주어진다. k-distant 인덱스는 테이블의 인덱스 i에 대해 |i - j| <= k이고 nums[j] == key를 만족하는 인덱스 j가 적어도 하나 존재하는 경우이다.
모든 k-distant 인덱스를 오름차순으로 정렬한 리스트를 반환해라.

Example

#1
Input: nums = [3, 4, 9, 1, 3, 9, 5], key = 9, k = 1
Output: [1, 2, 3, 4, 5, 6]

#2
Input: nums = [2, 2, 2, 2, 2], key = 2, k = 2
Output: [0, 1, 2, 3, 4]

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • key는 배열 numsd에 있는 정수이다.
  • 1 <= k <= nums.length

Solved

class Solution {
    public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
        List<Integer> result = new ArrayList<>();
        int n = nums.length;

        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(nums[j] == key && Math.abs(i - j) <= k){
                    result.add(i);
                    break;
                }
            }
        }

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

0개의 댓글