Skip to content

Commit 274439d

Browse files
authored
Create counting-elements.py
1 parent 0d60a2a commit 274439d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Python/counting-elements.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def countElements(self, arr):
6+
"""
7+
:type arr: List[int]
8+
:rtype: int
9+
"""
10+
lookup = set(arr)
11+
return sum(1 for x in arr if x+1 in lookup)
12+
13+
14+
# Time: O(nlogn)
15+
# Space: O(1)
16+
class Solution(object):
17+
def countElements(self, arr):
18+
"""
19+
:type arr: List[int]
20+
:rtype: int
21+
"""
22+
arr.sort()
23+
result, l = 0, 1
24+
for i in xrange(len(arr)-1):
25+
if arr[i] == arr[i+1]:
26+
l += 1
27+
continue
28+
if arr[i]+1 == arr[i+1]:
29+
result += l
30+
l = 1
31+
return result

0 commit comments

Comments
 (0)