LeetCode 355. Design Twitter(设计Twitter)

34 篇文章 0 订阅
33 篇文章 0 订阅

原题网址:https://leetcode.com/problems/design-twitter/

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:

  1. postTweet(userId, tweetId): Compose a new tweet.
  2. getNewsFeed(userId): 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.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. unfollow(followerId, followeeId): Follower unfollows a followee.

Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

方法:需要定义用户User、列表Feed和推文Tweet三个数据结构,使用哈希映射保存。

public class Twitter {
    private Map<Integer, User> map = new HashMap<>();

    /** Initialize your data structure here. */
    public Twitter() {
        
    }
    
    private User getUser(int userId) {
        User user = map.get(userId);
        if (user == null) {
            user = new User(userId);
            map.put(userId, user);
        }
        return user;
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        User user = getUser(userId);
        user.tweets.add(new Tweet(tweetId));
    }
    
    /** Retrieve the 10 most recent UserTweet 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. UserTweets must be ordered from most recent to least recent. */
    public List<Integer> getNewsFeed(int userId) {
        List<Integer> feeds = new ArrayList<>(10);
        User user = getUser(userId);
        List<User> users = new ArrayList<>();
        users.add(user);
        users.addAll(user.follows);

        PriorityQueue<Feed> heap = new PriorityQueue<>(new Comparator<Feed>() {
            @Override
            public int compare(Feed f1, Feed f2) {
                return f2.user.tweets.get(f2.pos).timestamp - f1.user.tweets.get(f1.pos).timestamp;
            }
        });
        
        for(User us : users) {
            if (us.tweets.isEmpty()) continue;
            Collections.sort(us.tweets, new Comparator<Tweet>() {
                @Override
                public int compare(Tweet t1, Tweet t2) {
                    return t1.timestamp - t2.timestamp;
                }
            });
            heap.offer(new Feed(us));
        }
        while (feeds.size() < 10 && !heap.isEmpty()) {
            Feed feed = heap.poll();
            feeds.add(feed.user.tweets.get(feed.pos).tweetId);
            if (--feed.pos >= 0) heap.offer(feed);
        }
        return feeds;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        User f1 = getUser(followerId);
        User f2 = getUser(followeeId);
        if (followerId == followeeId) return;
        f1.follows.add(f2);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        User f1 = getUser(followerId);
        User f2 = getUser(followeeId);
        if (followerId == followeeId) return;
        f1.follows.remove(f2);
    }
}

class User {
    int userId;
    List<Tweet> tweets = new ArrayList<>();
    Set<User> follows = new HashSet<>();
    User(int userId) {
        this.userId = userId;
    }
}

class Tweet {
    private static int count = 0;
    int tweetId;
    int timestamp;
    Tweet(int tweetId) {
        this.tweetId = tweetId;
        this.timestamp = count ++;
    }
}

class Feed {
    User user;
    int pos;
    Feed(User user) {
        this.user = user;
        this.pos = user.tweets.size()-1;
    }
}
/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postUserTweet(userId,tweetId);
 * List<Integer> param_2 = obj.getNewsFeed(userId);
 * obj.follow(followerId,followeeId);
 * obj.unfollow(followerId,followeeId);
 */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值