Given an array of integers nums and an integer k, determine whether there are two distinct indices i and j in the array where nums[i] = nums[j] and the absolute difference between i and j is less than or equal to k.

Example

Input/Output

풀이

boolean solution(int[] nums, int k) {
    // 요소와 해당 인덱스를 저장할 해시맵을 생성
    Map<Integer, Integer> map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        int num = nums[i];
        
        // 현재 요소가 해시맵에 이미 존재하는지 확인
        if (map.containsKey(num)) {
            // 인덱스 간의 절대 차이가 k 이하인지 확인. 그렇다면 true를 반환.
            if (i - map.get(num) <= k) {
                return true;
            }
        }
        
        // 현재 요소에 대한 해시맵의 인덱스를 업데이트.
        map.put(num, i);
    }

    // 이 조건을 만족하는 쌍을 찾지 못하면 false를 반환.
    return false;
}