![](https://img-blog.csdnimg.cn/20201014180756926.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
hash表
aaaqqq1234
这个作者很懒,什么都没留下…
展开
-
和为K的子数组
input: 5 4 1 2 1 3 4 output: 3 def fun(array,num,target): ans = 0 sum_dict = {0:1} sum_temp = 0 for i in range(num): sum_temp += array[i] ans += sum_dict.get(sum_temp-target,0) sum_dict[sum_temp] = sum_dict.get(sum_t原创 2020-09-11 11:13:49 · 62 阅读 · 0 评论 -
寻找主元素
题目 寻找数组里大于二分之一(n)的元素 思路 用hash表 代码 def main_element(list1): freq = {} list2 = [] length = len(list1) for i in list1: freq[i] = freq.get(i,0)+1 print(freq) for key,value in freq.items(): if value>length/2:原创 2020-08-04 17:35:40 · 86 阅读 · 0 评论 -
珠宝和石头
题目 J = ‘aA’,S = ‘aAAbbbb’ return 3 思路 把j放到set里,for 循环s 判断并计数 代码 def jewelstone(j,s): setj = set(j) count = 0 for i in s: if i in setj: count +=1 return count原创 2020-07-21 16:34:52 · 86 阅读 · 0 评论 -
求两个数组公共集合
题目 [1,2,2,1] ,[2,2] return [2,2] 思路 hash表 代码 def common_str(list1,list2): hash1 = {} for i in list1: hash1[i] = 1 + hash1.get(i,0) list = [] for j in list2: if j in hash1 and hash1[j]>0: list.append(j) hash1[j] -= 1 return原创 2020-07-20 22:56:26 · 294 阅读 · 0 评论 -
找两个数组公共集合
题目 [1,2,2,1] ,[2,2] return [2,2] 思路 1.set() 2.双指针 代码 def common_str(list1,list2): setA = set() setB = set() for i in list1: setA.add(i) for i in list2: setB.add(i) c = setA & setB print(c) def common_str(list1,list2): list1.sort(原创 2020-07-20 22:45:27 · 216 阅读 · 0 评论 -
找到第一个唯一的字符
题目 在一个字符串里找到第一个唯一的字符 思路 构建hash表,第一个出现value等于1的key 代码 def unique_frist(s): freq = {} for p in s: word = ''.join(c for c in p if p.isalpha()) if word: freq[word] = 1 + freq.get(word,0) for key,value in freq.items(): if value == 1:原创 2020-07-20 21:59:41 · 79 阅读 · 0 评论 -
单词计数
题目 单词计数 思路 hash表 代码 def wordcount(s): freq = {} for i in s.split(): freq[i] = 1 + freq.get(i,0) max_word = '' max_count = 0 for key,value in freq.items(): if value>max_count: max_count = value max_word = key print(max_cou原创 2020-07-20 21:49:47 · 57 阅读 · 0 评论 -
letter count
题目 找出字母出现最多的字母 思路 用hash表 代码 def lettercount(s): freq = {} for p in s: word = ''.join(c for c in p if c.isalpha()) if word: freq[word] = 1 + freq.get(word,0) max_word = '' max_count = 0 for key,value in freq.items(): if value>原创 2020-07-20 21:36:12 · 224 阅读 · 0 评论