1.문제
Contains Duplicate II - LeetCode
Can you solve this real interview question? Contains Duplicate II - 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. Example 1: Input: nums
leetcode.com
2.문제설명
주어진 배열에서 k 값 만큼 차이가 나는 경우 true 값을 반환 하는 형식이다.

3.소스코드
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> idx = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (idx.containsKey(nums[i]) && i - idx.get(nums[i]) <= k) {
return true;
}
idx.put(nums[i], i);
}
return false;
}
}
4.소스코드설명
이문제는 간격을 구하기 위한 HashMap 과 주어진 배열을 순회하는 방법을 사용하였다
TwoSum 문제에서 HashTable을 사용한 문제를 활용하였다
HashMap 에 추가를 하면서 HashMap 키를 찾아 가면서 nums 배열을 순회 하면서 idx 위치와 가져온 값을 뺀 값이 거리에 포함되는지 여부를 체크합니다.
'Algorithm' 카테고리의 다른 글
| [leetCode 242번] Valid Anagram (Java) (0) | 2023.08.31 |
|---|---|
| [leetCode 383번] Ransom Note(Java) (0) | 2023.08.31 |
| [leetCode 1번] Two Sum (Java) (0) | 2023.08.31 |
| [leetCode 155] Min Stack (Java) (0) | 2023.08.30 |
| [leetCode 74번] Search a 2D Matrix (Java) (0) | 2023.08.28 |