Skip to content

Commit c326c52

Browse files
My solution to leet code problems!
1 parent 19f4532 commit c326c52

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

217_Contains_Duplicate.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
""""
2+
217. Contains Duplicate
3+
4+
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
5+
6+
7+
8+
Example 1:
9+
10+
Input: nums = [1,2,3,1]
11+
Output: true
12+
13+
Example 2:
14+
15+
Input: nums = [1,2,3,4]
16+
Output: false
17+
18+
Example 3:
19+
20+
Input: nums = [1,1,1,3,3,4,3,2,4,2]
21+
Output: true
22+
"""
23+
24+
class Solution(object):
25+
def containsDuplicate(self, nums):
26+
"""
27+
:type nums: List[int]
28+
:rtype: bool
29+
"""
30+
dict1 = {}
31+
for i in range(len(nums)):
32+
if nums[i] in dict1:
33+
return True
34+
else:
35+
dict1[nums[i]] = 1
36+
return False

219_Contains_Duplicate II

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
219. Contains Duplicate II
3+
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.
4+
5+
6+
7+
Example 1:
8+
9+
Input: nums = [1,2,3,1], k = 3
10+
Output: true
11+
12+
Example 2:
13+
14+
Input: nums = [1,0,1,1], k = 1
15+
Output: true
16+
17+
Example 3:
18+
19+
Input: nums = [1,2,3,1,2,3], k = 2
20+
Output: false
21+
22+
"""
23+
class Solution(object):
24+
def containsNearbyDuplicate(self, nums, k):
25+
"""
26+
:type nums: List[int]
27+
:type k: int
28+
:rtype: bool
29+
"""
30+
dict1 = {}
31+
32+
for i in range(len(nums)):
33+
if nums[i] in dict1:
34+
return True
35+
else:
36+
dict1[nums[i]]=i
37+
if (len(dict1))>k:
38+
dict1.pop(nums[i-k])
39+
40+
41+
return False

0 commit comments

Comments
 (0)