219. Contains Duplicate II, 자바 풀이

이원석·2023년 9월 1일

Leetcode

목록 보기
13/22

[문제]
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

https://leetcode.com/problems/contains-duplicate-ii/?envType=study-plan-v2&envId=top-interview-150


class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i]) == null) {
                map.put(nums[i], i);
            } else {
                if (Math.abs(map.get(nums[i]) - i) <= k) {
                    return true;
                } else {
                    map.put(nums[i], i);
                }
            }
        }

        return false;
    }
}

// 중복되는 요소의 값 사이의 길이(인덱스간의 차)가 k이하인 것이 있으면 true를 return 한다.
// HashMap을 통해 해결해보자.
// 1. 만약 해당 Key값이 없다면, map에 추가하자.
// 2. 만약 해당 Key값이 있다면, 현재 인덱스와 해당 Key의 value(이전 인덱스)의 차를 구하자.
// 2-1. 해당 Key값의 Value는 현재 인덱스로 초기화 하자.

0개의 댓글