602. Friend Requests II: Who Has Most Friend?
来源:互联网 发布:虚空掠夺者数据库 编辑:程序博客网 时间:2024/06/06 00:48
Question
In social network like Facebook or Twitter, people send friend requests and accept others' requests as well.Tablerequest_accepted
holds the data of friend acceptance, while requester_id and accepter_id both are the id of a person.| requester_id | accepter_id | accept_date||--------------|-------------|------------|| 1 | 2 | 2016_06-03 || 1 | 3 | 2016-06-08 || 2 | 3 | 2016-06-08 || 3 | 4 | 2016-06-09 |Write a query to find the the people who has most friends and the most friends number. For the sample data above, the result is:| id | num ||----|-----|| 3 | 3 |Note:It is guaranteed there is only 1 people having the most friends. The friend request could only been accepted once, which mean there is no multiple records with the same requester_id and accepter_id value.Explanation:
The person with id '3' is a friend of people '1', '2' and '4', so he has 3 friends in total, which is the most number than any others.Follow-up:
In the real world, multiple people could have the same most number of friends, can you find all these people in this case?
Quick Navigation
- Solution
- Approach: Union requester_id and accepter_id [Accepted]
Solution
Approach: Union requester_id and accepter_id [Accepted]
Algorithm
Being friends is bidirectional, so if one person accepts a request from another person, both of them will have one more friend.
Thus, we can union column requester_id and accepter_id, and then count the number of the occurrence of each person.
select requester_id as ids from request_acceptedunion allselect accepter_id from request_accepted;
Note: Here we should use
union all
instead ofunion
becauseunion all
will keep all the records even the 'duplicated' one.
Taking the sample as an example, the output is:
Then it will be fairly easy to get the 'ids' with most occurrence using the same technique as mentioned in problem 580. Customer Placing the Largest Number of Orders.
MySQL
select ids as id, cnt as numfrom(select ids, count(*) as cnt from ( select requester_id as ids from request_accepted union all select accepter_id from request_accepted ) as tbl1 group by ids ) as tbl2order by cnt desclimit 1;
阅读全文
0 0
- 602. Friend Requests II: Who Has Most Friend?
- friend
- friend
- Friend
- Friend
- friend
- friend
- Friend
- friend
- Friend
- Friend
- friend
- ZOJ 3336 Friend Number II
- ZOJ 3336 Friend Number II
- zoj 3336 Friend Number II(水~)
- zoj 3336 Friend Number II(数论)
- friend webpage
- friend 函数
- cookie和session的区别!
- 将char *类型数据转变成oc数据
- unity中几个系统自带的函数的执行顺序
- mysql创建自增字段
- B
- 602. Friend Requests II: Who Has Most Friend?
- React-Native撸android原生百度定位SDK服务[跨平台模块自定义]
- 使用分区助手扩大系统盘容量
- Java+opencv3.2.0之灰度化
- CSM和PMI-ACP认证有什么区别
- Qt Little Tips
- oracle创建实例
- 分数加减法
- Jquery Table 的基本操作