0
点赞
收藏
分享

微信扫一扫

[leetcode] 1311. Get Watched Videos by Your Friends

非凡兔 2022-08-12 阅读 27


Description

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

Example 1:

[leetcode] 1311. Get Watched Videos by Your Friends_python

Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
The sister has three different kinds of candies.

Example 2:

[leetcode] 1311. Get Watched Videos by Your Friends_参考文献_02

Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
The sister has two different kinds of candies, the brother has only one kind of candies.

Note:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].

分析

题目的意思是:这道题要找出id的朋友看的视频,并按照频率从小到大输出。思路很直接,构建一个friend图,层序遍历找到id的friend,然后找出其看的video,进行排序就行了。

代码

class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
graph=collections.defaultdict(list)
for i,friend in enumerate(friends):
for item in friend:
graph[i].append(item)
i=0
q=collections.deque()
q.append(id)
s=set()
s.add(id)
while(i<level):
n=len(q)
for j in range(n):
val=q.popleft()
for item in graph[val]:
if(item not in s):
s.add(item)
q.append(item)
i+=1
d=collections.defaultdict(int)
while(q):
val=q.popleft()
for item in watchedVideos[val]:
d[item]+=1

return [k for _,k in sorted((v,k) for k,v in d.items())]

参考文献

​​[LeetCode] [Python3] Breadth-first search​​


举报

相关推荐

0 条评论