classSolution(object): defgroupAnagrams(self, strs): hashtable = {} for s in strs: fenlei = ''.join(sorted(s)) if fenlei notin hashtable: hashtable[fenlei] = [s] else: hashtable[fenlei].append(s) returnlist(hashtable.values())
最长连续序列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): deflongestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ hashtable = set(nums) ls = 0 for n in nums: if n - 1notin hashtable: i = n while i in hashtable: i += 1 ls = max(ls, i - n) return ls
好像太慢了额,看了眼官方题解,虽然我觉得没差,但是或许系统会给点优待
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): deflongestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ hashtable = set(nums) ls = 0 for n in nums: if n - 1notin hashtable: i = n cs = 1 while i + 1in hashtable: i += 1 cs += 1 ls = max(ls, cs) return ls