【力扣·设计推特】java实现

题目

设计一个简化版的推特(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);

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/design-twitter

源码

面向对象实现
Tweet类

class Tweet{
    private int id;
    private int time;
    public Tweet(int id,int time){
        this.id = id;
        this.time = time;
    }
    public int getId(){
        return this.id;
    }
    public int getTime(){
        return this.time;
    }
}

用户类

class User{
    private int id;
    private List<Tweet> tweet;
    private List<Integer> follows;

    public User(int id){
        this.id = id;
        this.tweet = new ArrayList<>();
        this.follows = new ArrayList<>();
    }

    public void follow(int followeeId){
        if(followeeId == id)
            return;
        for(int i = 0;i<follows.size();i++){
            if(follows.get(i) == followeeId)
                return;
        }
        follows.add(followeeId);
    }

    public void unfollow(int followeeId){
        if(!follows.contains(followeeId) || followeeId == id)
            return;
        for(int i = 0;i<follows.size();i++){
            if(follows.get(i) == followeeId){
                follows.remove(i);
                i--;
            }
        }
    }


    public void post(int tweetId,int time){
        Tweet tweets = new Tweet(tweetId,time);
        tweet.add(tweets);
    }

    public List<Tweet> getTweets(){
        return this.tweet;
    }
    public List<Integer> getFollows(){
        return this.follows;
    }
}

主类

class Twitter {
    private Map<Integer, User> user_map; //哈希表<用户ID,用户对象>
    private int global_time; //全局时间,用于标记推特发送时间

    /** Initialize your data structure here. */
    public Twitter() {
        this.user_map = new HashMap<Integer,User>();
        this.global_time = 0;
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        if(!user_map.containsKey(userId)){
            user_map.put(userId,new User(userId));
        }
        user_map.get(userId).post(tweetId,++global_time);
    }
    
    /** 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> list = new ArrayList<>();

        if(!user_map.containsKey(userId)) return list;

        List<Tweet> bridge = new ArrayList<>();
        List<Tweet> source = new ArrayList<>();
        source = user_map.get(userId).getTweets();
        //将用户本人发送的所有推特复制到brige
        for(int i = 0;i < source.size();i++){
            bridge.add(source.get(i));
        }
        //遍历用户关注的用户,将他们发送的推特复制到brige
        List<Integer> sourceOwner = user_map.get(userId).getFollows();
        for(int j = 0; j <sourceOwner.size();j++){
        	//注意该用户可能没有关注用户,省去判断会造成空指针引用
            if(!user_map.containsKey(sourceOwner.get(j)))
                continue;
            source = user_map.get(sourceOwner.get(j)).getTweets();
            for(int i = 0; i <source.size();i++){
                bridge.add(source.get(i));
            }
        }
        //对brige中的推特按照发送时间进行排序
        Collections.sort(bridge,new Comparator<Tweet>(){
            public int compare(Tweet t1,Tweet t2){
            	//按照发送时间进行降序排列
                if(t1.getTime() < t2.getTime())
                    return 1;
                if(t1.getTime() == t2.getTime())
                    return 0;
                return -1;
            }
        });
		//将前10条推特ID复制到list
        for(int i = 0;i < bridge.size()&&i<10;i++){
            list.add(bridge.get(i).getId());
        }
        
        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(!user_map.containsKey(followerId)){
            user_map.put(followerId,new User(followerId));
        }

        user_map.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(!user_map.containsKey(followerId)) return;

        user_map.get(followerId).unfollow(followeeId);
    }
}

今日收获

  1. List仅仅是一个接口,有多个实现类,包括ArrayList、LinkedList在内。
  2. 对List进行排序可以使用Collections.sort()方式,可以在参数中指定排序方式。
  3. 删除List中的指定值:
for(int i = 0;i<List对象.size();i++){
            if(List对象.get(i) == 指定值){
               List对象.remove(i);
                i--; //由其remove()方法的特性决定。删除后下标相对后移一位
            }
        }
  1. 哈希表。Map<Key,Value> map = new HashMap<Key,Value>();Map也有多个实现类如HashMap,TreeMap。
    常用方法
get(Object key) 返回键映射的值,如果该键没有映射值,则返回null
put(K key, V value) 将键和值建立映射关系,如果键是第一次存储,就直接存储元素,返回null; 如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
remove(Object key) 如果对应键存在映射关系的值,则将其移除,并返回值
containsKey(Object key) 是否存在特定的key
containsValue(Object value) 是否存在特定的value
isEmpty() 判断集合是否为空
keySet() 获取集合中所有键的集合 返回类型Set
values() 获取集合中所有值的集合 返回类型Collections
clear() 移除所有的Entry(键值对)
size() 返回集合中的键值对的对数
  1. 判断list集合中是否包含某元素:List的元素是一个类,使用contains()方法判断是否存在某个元素,需要重写该类的equals()方法。
    一般形式:
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        类名 变量名 = (类名) o;
        return Objects.equals(属性1, 变量名.属性1) &&
                Objects.equals(属性2, 变量名.属性2);
 	 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值