# 解题思路
两个内部类 用户和推文 用户有两个序表,一个存关注对象id,一个存自己发的推特id 推文两个属性,一个是id,一个是利用一个全局变量time生成的t,用来判断顺序 而主类中只有一个属性:用户数组,本来是链表的,但苦于无法将id与用户对应,又觉得链表索引id太慢了,就干脆用数组 先申请一个较大的空间,典型用空间换效率,有取巧的嫌疑,但是确实没办法 其他要注意的就是生成NewsFeed的时候,利用Collections.sort重载依据推文的t来排序,而待排序列由用户的所有关注对象和自己组成
# 代码
public class Twitter {
users[] userlist = new users[1000];
int time = 0;
public class twit {
int twittid;
int t;
int gettime(){
return t;
}
twit(int id) {
twittid = id;
time++;
t=time;
}
}
public class users {
List<Integer> followees = new ArrayList<>();
List<twit> twitts = new ArrayList<>();
public void setTwitts(Integer twitt) {
this.twitts.add(new twit(twitt));
}
public List<Integer> getTwitts() {
List<twit> copy1=new ArrayList<>();
copy1.addAll(twitts);
for (Integer f : followees) {
if(userlist[f]!=null)
copy1.addAll(userlist[f].twitts);
}
Collections.sort(copy1, new Comparator<twit>() {
public int compare(twit o1, twit o2) {
return o2.gettime() - o1.gettime();
}
});
List<Integer> temp = new ArrayList<>();
for (twit i : copy1
) {
temp.add(i.twittid);
}
return temp.size() < 10 ? temp : temp.subList(0, 10);
}
}
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
if (userlist[userId] == null) {
users newuser = new users();
newuser.setTwitts(tweetId);
userlist[userId] = newuser;
} else userlist[userId].setTwitts(tweetId);
}
public List<Integer> getNewsFeed(int userId) {
if (userlist[userId] == null) {
userlist[userId] = new users();
}
return userlist[userId].getTwitts();
}
public void follow(int followerId, int followeeId) {
if (userlist[followerId] == null) {
userlist[followerId] = new users();
}
if(followeeId==followerId)
return;
if (userlist[followerId].followees.contains(followeeId))
return;
else userlist[followerId].followees.add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
if (userlist[followerId] == null) {
userlist[followerId] = new users();
}
if(followeeId==followerId)
return;
if (userlist[followerId].followees.contains(followeeId))
userlist[followerId].followees.remove((Integer) followeeId);
else return;
}
}