Python每日一题系列 —— 今日挑战详解
又看到一个有意思的题 所以再更一道每日一题 然后我就继续看会儿算法去
给你一个二维字符串数组 responses,其中每个 responses[i] 是一个字符串数组,表示第 i 天调查的回答结果。
请返回在对每个 responses[i] 中的回答 去重 后,所有天数中 最常见 的回答。如果有多个回答出现频率相同,则返回 字典序最小 的那个回答。
根据题目要求 首先进行去重
class Solution(object):
def findCommonResponse(self, responses):
unique_responses = [list(dict.fromkeys(sub_list)) for sub_list in responses]
#这句话是对于二维字符串数组中的每个数组 使用dict.fromkeys进行去重
print(unique_responses)
solution=Solution()
result=solution.findCommonResponse([["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]])
print(result)
这有输出的结果每个字符串数组中的字符串都会是唯一的
然后进行计数 我的思想还是使用字典进行存储 然后看谁的value值是最大的 遍历数组 这个思想很好想
class Solution(object):
def findCommonResponse(self, responses):
unique_responses = [list(dict.fromkeys(sub_list)) for sub_list in responses]
#这句话是对于二维字符串数组中的每个数组 使用dict.fromkeys进行去重
dict1={}
for i in range(len(unique_responses)):
for j in range(len(unique_responses[i])):
key=unique_responses[i][j]
if key not in dict1:
dict1[key]=1
else:
dict1[key] += 1
return dict1
solution=Solution()
result=solution.findCommonResponse([["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]])
print(result)
然后就是常规操作 找到value值最大的那个key
class Solution(object):
def findCommonResponse(self, responses):
unique_responses = [list(dict.fromkeys(sub_list)) for sub_list in responses]
#这句话是对于二维字符串数组中的每个数组 使用dict.fromkeys进行去重
dict1={}
for i in range(len(unique_responses)):
for j in range(len(unique_responses[i])):
key=unique_responses[i][j]
if key not in dict1:
dict1[key]=1
else:
dict1[key] += 1
max_key = max(dict1, key=lambda k: dict1[k])
return max_key
solution=Solution()
result=solution.findCommonResponse([["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]])
print(result)
但是题目的要求是如何出现了相同的最大次数的 就要返回字典序最小 的那个回答
思路就是将最大的value值拿出来 然后找最大value值对应的key 存到一个列表里面 然后使用一个min就可以找到最小字典序的了
class Solution(object):
def findCommonResponse(self, responses):
unique_responses = [list(dict.fromkeys(sub_list)) for sub_list in responses]
#这句话是对于二维字符串数组中的每个数组 使用dict.fromkeys进行去重
dict1={}
for i in range(len(unique_responses)):
for j in range(len(unique_responses[i])):
key=unique_responses[i][j]
if key not in dict1:
dict1[key]=1
else:
dict1[key] += 1
max_value = max(dict1.values())#返回最大的value值
nums=[]
for i in dict1:
if dict1[i]==max_value:
nums.append(i)#此时得到一个列表 里面存储的是value值最大的key
return min(nums)
solution=Solution()
result=solution.findCommonResponse([["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]])
print(result)
感觉这个题的思路还是很简单的 就是可能会比较容易绕迷糊 这个题我的测试结果是运行速度超过87% 消耗内存超过69% 感觉是个还可以的结果 我没有看运行最小的情况是啥样的 私以为自己想的这个办法还蛮简单 还是挺好理解的
欢迎各位评论区一起讨论呀!
作者:m0_62653520