https://leetcode.com/problems/contains-duplicate-ii/description
Q. 정수 배열 nums와 정수 k 가 주어질 때, 그 값이 같고 index차이가 k보다 같거나 작은 두 원소가 존재하는지 찾아라.
Solution
역시, 말이 복잡해 보이지, 조건 자체는 간단하다.
같은 원소 중 위치 차이가 k 이하로 나는 두 원소를 찾는다.
public bool ContainsNearbyDuplicate(int[] nums, int k)
{
Dictionary<int, List<int>> dictBuff = new Dictionary<int, List<int>>();
for(int q = 0; q < nums.Length; ++q)
{
int cur = nums[q];
if(!dictBuff.ContainsKey(cur))
dictBuff.Add(cur, new List<int>());
else
{
for(int z = 0; z < dictBuff[cur].Count; ++z)
{
if(q - dictBuff[cur][z] <= k)
return true;
}
}
dictBuff[cur].Add(q);
}
return false;
}
결과.
'Leetcode > Top Interview 150' 카테고리의 다른 글
[Stack][Medium] 71. Simplify Path (0) | 2024.05.10 |
---|---|
[Intervals][Easy] 228. Summary Ranges (0) | 2024.05.08 |
[Hashmap][Easy] 202. Happy Number (0) | 2024.05.07 |
[Hashmap][Medium] 49. Group Anagrams (0) | 2024.05.07 |
[Hashmap][Easy] 242. Valid Anagram (0) | 2024.05.06 |