Last active
April 7, 2020 19:11
-
-
Save rejoycesong/fca710955aba9bc2d5fb393f143fd7e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# no runtime given, but O(n) | |
class Solution: | |
def countElements(self, arr: List[int]) -> int: | |
seen = set(arr) | |
return sum([1 if n+1 in seen else 0 for n in arr]) | |
# 28ms with reduce; also O(n) | |
class Solution: | |
def countElements(self, arr: List[int]) -> int: | |
seen = set(arr) | |
return reduce(lambda accumulated, x: accumulated + (1 if x+1 in seen else 0), arr, 0) | |
# this one seems the fastest; didn't know you can sum over a generator directly without an iterable | |
class Solution: | |
def countElements(self, arr: List[int]) -> int: | |
seen = set(arr) | |
return sum(1 if n+1 in seen else 0 for n in arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment