【问题描述】355 设计推特

设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文。你的设计需要支持以下的几个功能:postTweet(userId, tweetId): 创建一条新的推文
getNewsFeed(userId): 检索最近的十条推文。每个推文都必须是由此用户关注的人或者是用户自己发出的。推文必须按照时间顺序由最近的开始排序。
follow(followerId, followeeId): 关注一个用户
unfollow(followerId, followeeId): 取消关注一个用户
示例:Twitter twitter = new Twitter();// 用户1发送了一条新推文 (用户id = 1, 推文id = 5).
twitter.postTweet(1, 5);// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
twitter.getNewsFeed(1);
// 用户1关注了用户2.
twitter.follow(1, 2);
// 用户2发送了一个新推文 (推文id = 6).
twitter.postTweet(2, 6);
// 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5].
// 推文id6应当在推文id5之前,因为它是在5之后发送的.
twitter.getNewsFeed(1);
// 用户1取消关注了用户2.
twitter.unfollow(1, 2);
// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
// 因为用户1已经不再关注用户2.
twitter.getNewsFeed(1);

【解答思路】

1. 设计思路


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;public class Twitter {/*** 用户 id 和推文(单链表)的对应关系*/private Map<Integer, Tweet> twitter;/*** 用户 id 和他关注的用户列表的对应关系*/private Map<Integer, Set<Integer>> followings;/*** 全局使用的时间戳字段,用户每发布一条推文之前 + 1*/private static int timestamp = 0;/*** 合并 k 组推文使用的数据结构(可以在方法里创建使用),声明成全局变量非必需,视个人情况使用*/private static PriorityQueue<Tweet> maxHeap;/*** Initialize your data structure here.*/public Twitter() {followings = new HashMap<>();twitter = new HashMap<>();maxHeap = new PriorityQueue<>((o1, o2) -> -o1.timestamp + o2.timestamp);}/*** Compose a new tweet.*/public void postTweet(int userId, int tweetId) {timestamp++;if (twitter.containsKey(userId)) {Tweet oldHead = twitter.get(userId);Tweet newHead = new Tweet(tweetId, timestamp);newHead.next = oldHead;twitter.put(userId, newHead);} else {twitter.put(userId, new Tweet(tweetId, timestamp));}}/*** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.*/public List<Integer> getNewsFeed(int userId) {// 由于是全局使用的,使用之前需要清空maxHeap.clear();// 如果自己发了推文也要算上if (twitter.containsKey(userId)) {maxHeap.offer(twitter.get(userId));}Set<Integer> followingList = followings.get(userId);if (followingList != null && followingList.size() > 0) {for (Integer followingId : followingList) {Tweet tweet = twitter.get(followingId);if (tweet != null) {maxHeap.offer(tweet);}}}List<Integer> res = new ArrayList<>(10);int count = 0;while (!maxHeap.isEmpty() && count < 10) {Tweet head = maxHeap.poll();res.add(head.id);// 这里最好的操作应该是 replace,但是 Java 没有提供if (head.next != null) {maxHeap.offer(head.next);}count++;}return res;}/*** Follower follows a followee. If the operation is invalid, it should be a no-op.** @param followerId 发起关注者 id* @param followeeId 被关注者 id*/public void follow(int followerId, int followeeId) {// 被关注人不能是自己if (followeeId == followerId) {return;}// 获取我自己的关注列表Set<Integer> followingList = followings.get(followerId);if (followingList == null) {Set<Integer> init = new HashSet<>();init.add(followeeId);followings.put(followerId, init);} else {if (followingList.contains(followeeId)) {return;}followingList.add(followeeId);}}/*** Follower unfollows a followee. If the operation is invalid, it should be a no-op.** @param followerId 发起取消关注的人的 id* @param followeeId 被取消关注的人的 id*/public void unfollow(int followerId, int followeeId) {if (followeeId == followerId) {return;}// 获取我自己的关注列表Set<Integer> followingList = followings.get(followerId);if (followingList == null) {return;}// 这里删除之前无需做判断,因为查找是否存在以后,就可以删除,反正删除之前都要查找followingList.remove(followeeId);}/*** 推文类,是一个单链表(结点视角)*/private class Tweet {/*** 推文 id*/private int id;/*** 发推文的时间戳*/private int timestamp;private Tweet next;public Tweet(int id, int timestamp) {this.id = id;this.timestamp = timestamp;}}public static void main(String[] args) {Twitter twitter = new Twitter();twitter.postTweet(1, 1);List<Integer> res1 = twitter.getNewsFeed(1);System.out.println(res1);twitter.follow(2, 1);List<Integer> res2 = twitter.getNewsFeed(2);System.out.println(res2);twitter.unfollow(2, 1);List<Integer> res3 = twitter.getNewsFeed(2);System.out.println(res3);}作者:liweiwei1419
链接:https://leetcode-cn.com/problems/design-twitter/solution/ha-xi-biao-lian-biao-you-xian-dui-lie-java-by-liwe/

【总结】

1.维护数据
  • 如果需要维护数据的时间有序性,链表在特殊场景下可以胜任。因为时间属性通常来说是相对固定的,而不必去维护顺序性;
  • 如果需要动态维护数据有序性,「优先队列」(堆)是可以胜任的;
2. maxHeap = new PriorityQueue<>((o1, o2) -> -o1.timestamp + o2.timestamp); 中的(o1, o2) -> -o1.timestamp + o2.timestamp
这里是 Java 的 lambda 表达式,等价于:Java 代码:maxHeap = new PriorityQueue<>(new Comparator<Tweet>() {@Overridepublic int compare(Tweet o1, Tweet o2) {return -o1.timestamp + o2.timestamp;}
});
lambda 表达式,它是把函数作为一个方法的参数的一种等价写法,可以认为是「语法糖」。在 IDEA 工具里面写匿名方法,然后再让 IDEA 帮助优化成 lambda 表达式。
3. 面向对象 注意细节 分级思考 想好再码

原文链接;https://leetcode-cn.com/problems/design-twitter/solution/ha-xi-biao-lian-biao-you-xian-dui-lie-java-by-liwe/

[Leedcode][JAVA][第355题][设计推特][面向对象][哈希表][链表][优先队列]相关推荐

  1. [Leedcode][JAVA][第45题][跳跃游戏 II][贪心算法]

    [问题描述][Leedcode][JAVA][第45题][跳跃游戏 II] 输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2.从下标为 0 跳到下标为 1 的位置 ...

  2. [Leedcode][JAVA][第105题][从前序与中序遍历序列构造二叉树][栈][递归][二叉树]

    [问题描述][中等] 根据一棵树的前序遍历与中序遍历构造二叉树.注意: 你可以假设树中没有重复的元素.例如,给出前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = ...

  3. [Leedcode][JAVA][第470题][Ran7()实现Rand10()]

    [问题描述][Leedcode][JAVA][第470题][Ran7()实现Rand10()] 已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 ...

  4. 如何设计散列表(哈希表)

    如何设计散列表(哈希表) 可以获取到什么 通过本章可以了解散列表是什么数据结构,为什么叫做散列表?他的特点是什么?以及如何去设计一个散列表?为什么要这么设计? 会介绍散列表中三个重要的核心点:散列函数 ...

  5. ​LeetCode刷题实战355:设计推特

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  6. [Leedcode][JAVA][第146题][LRU][哈希表][双向链表]

    [问题描述] LFU 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制.它应该支持以下操作: 获取数据 get 和 写入数据 put .获取数据 get(key) - 如果密 ...

  7. [Leedcode][JAVA][第560题][和为K的子数组][Hashmap][数组]

    [问题描述][第560题][和为K的子数组][中等] 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数.示例 1 :输入:nums = [1,1,1], k = 2 输 ...

  8. [Leedcode][JAVA][第460题][LFU]

    [问题描述] 设计并实现最不经常使用(LFU)缓存的数据结构.它应该支持以下操作:get 和 put.get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1. put(ke ...

  9. [Leedcode][JAVA][第974题][和可被K整除的子数组][前缀和][HashSet]

    [问题描述][中等] 给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续.非空)子数组的数目.示例:输入:A = [4,5,0,-2,-3,1], K = 5 输出:7 解释: 有 7 个子 ...

最新文章

  1. Android layout布局属性、标签属性总结大全
  2. python好学吗mooc中文网-Python语言程序设计
  3. PHP-代码审计-文件上传
  4. 用公式实现动态设置图表的轴数据项
  5. LoadRunner如何调用外部函数
  6. opencv 高通滤波和低通滤波_滤波电路合集(低通滤波,CLCП滤波,DLC滤波,CRC П滤波)...
  7. 一.路径规划---二维路径规划仿真实现-gmapping+amcl+map_server+move_base
  8. TikZ绘图示例——尺规作图:任意等分半圆弧
  9. PHP可不可以调用opengl库,opengl,_苹果能不能用 OpenGL 3 或以上写代码?,opengl - phpStudy...
  10. arm集群服务器_什么样的ARM处理器及内存配置适合用来开发ARM集群服务器?
  11. 软件安全测试的几个原则
  12. 超市也开始玩“内卷”?
  13. 集合类 collection接口 LinkedList
  14. Java的注解和反射
  15. php起点小说小偷程序,PHP小偷程序的简单示例
  16. SSM框架整合(参考尚硅谷视频和文档
  17. AdaDelta算法
  18. Volley 源码解析(一)
  19. OUTLOOK无法打开
  20. get和post详解

热门文章

  1. sharepoint安装心得_过程
  2. java做报表_一步一步使用POI做java报表
  3. php中for循环流程图,PHP for循环
  4. 认识 react 的钩子函数
  5. 面试必备:HashMap底层数据结构?jdk1.8算法优化,hash冲突,扩容等问题
  6. Android 截图,截取指定view截图
  7. Android ViewPager指示器
  8. 警惕Oracle DB操作高压线
  9. 使用SharpZipLib.dll压缩zip
  10. linux 线程间传送消息,Linux 多线程同步-消息队列