leetcode 探索 查找表类算法
1、给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
import collections def frequencySort(s): dic = dict(collections.Counter(s)) res = sorted(dic.items(),key = lambda item:item[1],reverse = True) temp = "" for i in res: temp +=i[0]*i[1] return temp s = "tree" print(frequencySort(s))
3: 三数之和。
def threeSum(nums): res = [] nums.sort() n = len(nums) #如果数组长度小于3,也就不存在三数之和,返回[] if n<3: return res #遍历数组: for i in range(n): #数组已完成排序,i 之后的元素不存在三数之和=0的情况 if nums[i]>0:
break #跳过相邻的重复元素。 if (i>0 and nums[i]==nums[i-1]): continue #初始化指针:令 i<l<r,然后进入循环。 l = i+1 r = n-1 while l<r: sum = nums[i]+nums[l]+nums[r] if sum==0: res.append([nums[i],nums[l],nums[r]]) #去重 while (l<r and nums[l]==nums[l+1]): l = l+1 while (l<r and nums[r]==nums[r-1]): r = r-1 l = l+1 r = r-1 elif sum>0: r = r-1 else: l = l+1 return res nums = [-1, 0, 1, 2, -1, -4] print(threeSum(nums))
4、给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
输入:["eat", "tea", "tan", "ate", "nat", "bat"] 输出:[
["ate","eat","tea"],["nat","tan"],["bat"]].
算法:将字母异位词的组成字母以元组的形式构成键(key),字母异位词以列表形式构成值(value).例如:dic = {(a,e,t):["eat","tea","ate"]}
def groupAnagrams(strs): dic = {} for i in strs: res = tuple(sorted(i)) if res in dic.keys(): dic[res].append(i) else: dic[res] = [i] return list(dic.values()) strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print(groupAnagrams(strs))