Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fe46566

Browse files
committed
Add Solution.py for problems 0219
1 parent 1091fee commit fe46566

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'''
2+
https://leetcode.com/problems/contains-duplicate-ii/
3+
4+
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
5+
'''
6+
'''
7+
Runtime: 96 ms, faster than 93.53% of Python3 online submissions for Contains Duplicate II.
8+
Memory Usage: 20.5 MB, less than 62.50% of Python3 online submissions for Contains Duplicate II.
9+
'''
10+
11+
# Create a hashmap to remember the most recent position of unique values
12+
# If we found duplicate and the range is less than k, then return true
13+
# Else remember that index
14+
class Solution:
15+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
16+
pos = {}
17+
for idx, element in enumerate(nums):
18+
if element in pos and idx - pos[element] <= k:
19+
return True
20+
pos[element] = idx
21+
return False
22+
23+
24+
25+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /