Description
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1:
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
Example 2:
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
Example 3:
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]
Constraints:
- 1 <= favoriteCompanies.length <= 100
- 1 <= favoriteCompanies[i].length <= 500
- 1 <= favoriteCompanies[i][j].length <= 20
- All strings in favoriteCompanies[i] are distinct.
- All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
= All strings consist of lowercase English letters only.
分析
题目的意思是:给定一个公司列表,找出公司列表里面非子集合的索引,即其中的一个集合不是列表中其他集合的子集。我参考了一下别人的思路,大概是这样,先把公司列表变成集合,然后遍历判断是否是子集,如果是则跳过,否则把索引加入到结果集合res中。python中集合是可以比较的哈,可以判断一个集合是否是另一个集合的子集。
代码
class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
array_of_sets=[set(item) for item in favoriteCompanies]
n=len(favoriteCompanies)
res=[]
for i in range(n):
flag=True
for j in range(n):
if(i!=j):
if(array_of_sets[i] < array_of_sets[j]):
flag=False
break
if(flag):
res.append(i)
return res
参考文献
[LeetCode] Python solution using set, easy_to_understand to pythonic