Contains Duplicate II

bong bong·2023년 9월 1일

알고리즘

목록 보기
16/31

문제

정수 배열 nums과 정수가 주어지면 두 개의 서로 다른 인덱스가 있고 배열에 및 가 있는 경우k 반환됩니다 .true ijnums[i] == nums[j]abs(i - j) <= k

구현 생각

HashMap을 사용하여 요소와 해당 인덱스의 매핑을 저장합니다.
Map<Integer, Integer> indexMap = new HashMap<>();

배열을 반복하며 각 요소에 대해 맵에 이미 있는지 확인하고, 만약 그렇다면 현재 인덱스와 저장된 인덱스의 차이가 지정된 범위 k 내에 있는지 확인합니다.
for (int i = 0; i < nums.length; i++) {
if (indexMap.containsKey(nums[i]) && Math.abs(i - indexMap.get(nums[i])) <= k) {
return true;
}
indexMap.put(nums[i], i);
}
그렇지 않으면 요소의 인덱스를 맵에 업데이트합니다. 유효한 쌍이 발견되지 않으면 false를 반환합니다.
return false;

구현 방법

public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> indexMap = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (indexMap.containsKey(nums[i]) && Math.abs(i - indexMap.get(nums[i])) <= k) {
                return true;
            }
            indexMap.put(nums[i], i);
        }
        
        return false;
    }
profile
let's go invent tomorrow rather than worrying about what happened yesterday - Steven Paul Jobs

0개의 댓글