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 5427c3f

Browse files
Merge pull request doocs#237 from phuclhv/master
Add Solution.py for problem 0219.Contains Duplicate II
2 parents 187f3cc + 167e713 commit 5427c3f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
# Performance
7+
'''
8+
Runtime: 96 ms, faster than 93.53% of Python3 online submissions for Contains Duplicate II.
9+
Memory Usage: 20.5 MB, less than 62.50% of Python3 online submissions for Contains Duplicate II.
10+
'''
11+
12+
# Algorithm Explained
13+
'''
14+
Create a hashmap to remember the most recent position of unique values
15+
If we found duplicate and the range is less than k, then return true
16+
Else remember that index
17+
18+
Space: O(n) with n is the number of original array
19+
Complexity: O(n)
20+
'''
21+
class Solution:
22+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
23+
pos = {}
24+
for idx, element in enumerate(nums):
25+
if element in pos and idx - pos[element] <= k:
26+
return True
27+
pos[element] = idx
28+
return False
29+
30+
31+
32+

0 commit comments

Comments
(0)

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