-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwitter.kt
62 lines (53 loc) · 1.8 KB
/
Twitter.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Twitter() {
inner class Tweet(
val userId: Int,
val tweetId: Int,
val timeLog: Int
)
private var tweetMap = hashMapOf<Int, ArrayList<Tweet>>()
private var friendMap = hashMapOf<Int, ArrayList<Int>>()
private var timeLog = 0
/** Compose a new tweet. */
fun postTweet(userId: Int, tweetId: Int) {
if (tweetMap.containsKey(userId).not())
tweetMap[userId] = arrayListOf()
tweetMap[userId]?.run {
add(Tweet(userId, tweetId, timeLog))
timeLog++
}
}
fun getNewsFeed(userId: Int): List<Int> {
val feeds = ArrayList<Tweet>()
tweetMap[userId]?.run {
feeds.addAll(this)
}
friendMap[userId]?.map { id ->
tweetMap[id]?.filter { it.userId == id }?.run {
feeds.addAll(this)
}
}
feeds.sortByDescending { it.timeLog }
return feeds.map { it.tweetId }.distinctBy { it }.take(10)
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
fun follow(followerId: Int, followeeId: Int) {
if (friendMap.containsKey(followerId).not())
friendMap[followerId] = arrayListOf()
friendMap[followerId]?.add(followeeId)
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
fun unfollow(followerId: Int, followeeId: Int) {
if (friendMap.containsKey(followerId).not())
return
else
friendMap[followerId]?.remove(followeeId)
}
}
/**
* Your Twitter object will be instantiated and called as such:
* var obj = Twitter()
* obj.postTweet(userId,tweetId)
* var param_2 = obj.getNewsFeed(userId)
* obj.follow(followerId,followeeId)
* obj.unfollow(followerId,followeeId)
*/