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
문제 설명
- 정수형 배열 nums가 주어진다.
- nums의 같은 두 수의 사이 간격이 k보다 작은 경우가 있으면 true, 없으면 false를 반환한다.
문제 해결
- 반복문을 앞에서부터 수의 값을 Key로 인덱스를 Value로 하도록 HashMap에 계속해서 갱신한다.
- 현재 수의 값과 동일한 Key를 가진 값이 있는 경우 현재 인덱스와 HashMap의 인덱스를 빼서 같은 두 수간 거리를 구한다.
- 이후 k보다 작거나 같은 경우가 있으면 true를 반환하고 없으면 반복문을 다 돌고 false 반환한다.
시간 복잡도
- O(N)
풀이 코드
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int N = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < N; i++) {
int now = nums[i];
if (map.containsKey(now)) {
int j = map.get(now);
int d = i - j;
if (d <= k) {
return true;
}
map.put(now, i);
} else {
map.put(now, i);
}
}
return false;
}
}
결과
시간 | 메모리 |
17 ms | 56.4 MB |
'알고리즘 > LeetCode' 카테고리의 다른 글
[알고리즘] LeetCode - Valid Anagram (0) | 2023.08.31 |
---|---|
[알고리즘] LeetCode - Ransom Note (0) | 2023.08.31 |
[알고리즘] LeetCode - Two Sum (0) | 2023.08.31 |
[알고리즘] LeetCode - Evaluate Reverse Polish Notation (0) | 2023.08.31 |
[알고리즘] LeetCode - Min Stack (0) | 2023.08.31 |