Skip to content

Commit e083213

Browse files
committed
Contains Duplicate/ Contains Duplicate II
1 parent 94dc3c8 commit e083213

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

217 Contains Duplicate.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'''
2+
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
3+
'''
4+
5+
class Solution(object):
6+
def containsDuplicate(self, nums):
7+
"""
8+
:type nums: List[int]
9+
:rtype: bool
10+
"""
11+
return len(nums) != len(set(nums))
12+
13+
14+
if __name__ == "__main__":
15+
assert Solution().containsDuplicate([1, 2, 3, 4]) == False
16+
assert Solution().containsDuplicate([1, 2, 3, 1]) == True

219 Contains Duplicate II.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'''
2+
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 difference between i and j is at most k.
3+
'''
4+
5+
class Solution(object):
6+
def containsNearbyDuplicate(self, nums, k):
7+
"""
8+
:type nums: List[int]
9+
:type k: int
10+
:rtype: bool
11+
"""
12+
if not nums:
13+
return False
14+
m = {}
15+
for i in range(len(nums)):
16+
if nums[i] in m:
17+
if i - m.get(nums[i]) <= k:
18+
return True
19+
m[nums[i]] = i
20+
return False
21+
22+
23+
if __name__ == "__main__":
24+
assert Solution().containsNearbyDuplicate([1, 2, 3, 4], 1) == False
25+
assert Solution().containsNearbyDuplicate([1, 1, 2, 3], 2) == True
26+
assert Solution().containsNearbyDuplicate([1, 2, 3, 1], 2) == False

0 commit comments

Comments
 (0)