力扣labuladong一刷day58天设计朋友圈时间线

力扣labuladong一刷day58天设计朋友圈时间线

一、355. 设计推特

题目链接:https://leetcode.cn/problems/design-twitter/description/
思路:采用面向对象的思想,构造user类和tweet类,tweet类中有一个time字段用于排序,user类记录该类关注的用户id和自己发推文的链表头结点,之后获取推文的时候,拿到该用户的关注列表中的所有用户,使用优先级队列来处理。思路和多链表合并差不多。

class Twitter {

    int time = 0;
    Map<Integer, User> map;


    public Twitter() {
        map = new HashMap<>();
    }

    public void postTweet(int userId, int tweetId) {
        if (!map.containsKey(userId)) {
            User user = new User(userId);
            map.put(userId, user);
        }
        map.get(userId).post(tweetId);
    }

    public List<Integer> getNewsFeed(int userId) {
        ArrayList<Integer> res = new ArrayList<>();
        if (!map.containsKey(userId)) return res;
        Set<Integer> set = map.get(userId).followed;
        PriorityQueue<Tweet> pq = new PriorityQueue<>(set.size(), (t1, t2) -> t2.time - t1.time);
        for (Integer i : set) {
            Tweet head = map.get(i).head;
            if (null == head) continue;
            pq.add(head);
        }
        while (!pq.isEmpty()) {
            if (res.size() == 10) break;
            Tweet poll = pq.poll();
            res.add(poll.id);
            if (poll.next != null) {
                pq.add(poll.next);
            }
        }
        return res;
    }

    public void follow(int followerId, int followeeId) {
        if (!map.containsKey(followerId)) {
            User user = new User(followerId);
            map.put(followerId, user);
        }
        if (!map.containsKey(followeeId)) {
            User user = new User(followeeId);
            map.put(followeeId, user);
        }
        map.get(followerId).follow(followeeId);
    }

    public void unfollow(int followerId, int followeeId) {
        if (map.containsKey(followerId)) {
            map.get(followerId).unfollow(followeeId);
        }
    }

    class User {
        int id;
        Set<Integer> followed;
        Tweet head;

        public User(int id) {
            this.id = id;
            this.followed = new HashSet<>();
            this.head = null;
            follow(id);
        }

        void follow(int id) {
            followed.add(id);
        }

        void unfollow(int id) {
            if (id != this.id) {
                followed.remove(id);
            }
        }

        void post(int tweedId) {
            Tweet tweet = new Tweet(tweedId, time++);
            tweet.next = head;
            head = tweet;
        }

    }
    class Tweet{
        int id;
        int time;
        Tweet next;

        public Tweet(int id, int time) {
            this.id = id;
            this.time = time;
            this.next = null;
        }
    }
}

你可能感兴趣的:(力扣算法题,leetcode,dreamweaver,算法)