Array
Problem
Solution
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
mem = set()
for num in nums:
if num in mem:
return True
mem.add(num)
return FalseSolution using Set since it optimize for check if element in set or not.
Problem
Solution
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
t_char = list(t)
for char in s:
try:
t_char.remove(char)
except:
return False
if len(t_char) != 0:
return False
return TrueProblem
Solution
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
mem = {}
for i, num in enumerate(nums):
if target - num in mem:
return i, mem[target - num]
mem[num] = iProblem
Solution
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ans = collections.defaultdict(list)
for word in strs:
count = [0]*26
for char in word:
count[ord(char) - ord('a')] += 1
ans[tuple(count)].append(word)
return ans.values()