JAVA程序设计: 设计推特(LeetCode: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);

 

思路:

方法一:(比较暴力),采用map存储每个用户关注的其他用户ID,再开一个栈存储每一条发送的推特以及相应ID,然后就能勉勉强强通过这道题了。

class Twitter {
	
	class node{
		int x,y;
		public node(int x,int y) {
			this.x=x;
			this.y=y;
		}
	}
	
	Map<Integer,List<Integer>> idMap;
	Stack<node> st;
	Stack<node> tmp;
	List<Integer> list;
	
    /** Initialize your data structure here. */
    public Twitter() {
    	idMap=new HashMap<>();
    	st=new Stack<node>();
    	tmp=new Stack<node>();
    	list=new ArrayList<>();
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
    	st.add(new node(userId,tweetId));
    }
    
    /** 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) {
    	int num=0;
    	list.clear();
    	while(!st.isEmpty() && num<10)
    	{
    		node now=st.pop();
    		if(idMap.containsKey(userId) && idMap.get(userId).contains(now.x) || userId==now.x)
    		{
    			num++;
    			list.add(now.y);
    		}
    		tmp.add(now);
    	}
    	while(!tmp.isEmpty()) 
    		st.add(tmp.pop());
    	return list;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        if(!idMap.containsKey(followerId))
        	idMap.put(followerId, new ArrayList<Integer>());
        idMap.get(followerId).add(followeeId);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        if(idMap.containsKey(followerId) && idMap.get(followerId).contains((Object)followeeId))
        	idMap.get(followerId).remove((Object)followeeId);
    }
}

方法二:(强力推荐)面向对象设计 + 合并 K 个有序链表的算法

非常棒的题解:LeetCode题解

class Twitter {
	
	private static int timestamp=0;
	private static class Tweet{
		private int id;
		private int time;
		private Tweet next;
		
		public Tweet(int id,int time) {
			this.id=id;
			this.time=time;
			this.next=null;
		}
	}
	private static class User{
		private int id;
		public Set<Integer> followed;
		public Tweet head;
		
		public User(int userId) {
			followed=new HashSet<>();
			this.id=userId;
			this.head=null;
			
			//关注一下自己
			follow(id);
		}
		
		public void follow(int userId) {
			followed.add(userId);
		}
		
		public void unfollow(int userId) {
			if(userId!=this.id)
				followed.remove(userId);
		}
		
		public void post(int tweetId) {
			Tweet twt=new Tweet(tweetId,timestamp);
			timestamp++;
			
			//将新建的推文插入到链表头
			//越靠前的推文time值越大
			twt.next=head;
			head=twt;
		}
	}
	
	private HashMap<Integer,User> userMap;
	
    /** Initialize your data structure here. */
    public Twitter() {
    	userMap=new HashMap<>();
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
    	if(!userMap.containsKey(userId))
    		userMap.put(userId, new User(userId));
    	User u=userMap.get(userId);
    	u.post(tweetId);
    }
    
    /** 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) {
    	List<Integer> res=new ArrayList<>();
    	if(!userMap.containsKey(userId)) return res;
    	Set<Integer> users=userMap.get(userId).followed;
    	PriorityQueue<Tweet> queue=new PriorityQueue<>(users.size(),(a,b)->(b.time-a.time));
    	
    	//先将所有链表的头结点插入优先队列
    	for(int id : users) {
    		Tweet twt=userMap.get(id).head;
    		if(twt==null) continue;
    		queue.add(twt);
    	}
    	
    	while(!queue.isEmpty()) {
    		if(res.size()==10)
    			break;
    		Tweet twt=queue.poll();
    		res.add(twt.id);
    		if(twt.next!=null)
    			queue.add(twt.next);
    	}
    	
    	return res;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        if(!userMap.containsKey(followerId)) {
        	User u=new User(followerId);
        	userMap.put(followerId, u);
        }
        if(!userMap.containsKey(followeeId)) {
        	User u=new User(followeeId);
        	userMap.put(followeeId, u);
        }
        userMap.get(followerId).follow(followeeId);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        if(userMap.containsKey(followerId))
        {
        	User flower=userMap.get(followerId);
        	flower.unfollow(followeeId);
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值