Skip to content

Commit 5909e1b

Browse files
add 355
1 parent 6bdac69 commit 5909e1b

File tree

3 files changed

+204
-0
lines changed

3 files changed

+204
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ Your ideas/fixes/algorithms are more than welcome!
149149
|360|[Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/)|[Solution](../master/src/main/java/com/stevesun/solutions/_360.java)| O(n)|O(1) | Medium| Two Pointers, Math
150150
|359|[Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/)|[Solution](../master/src/main/java/com/stevesun/solutions/LoggerRateLimiter.java)| amortized O(1)|O(k) | Easy| HashMap
151151
|357|[Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/)|[Solution](../master/src/main/java/com/stevesun/solutions/CountNumbersWithUniqueDigits.java)| O(?)|O(?) | Medium|
152+
|355|[Design Twitter](https://leetcode.com/problems/design-twitter/)|[Solution](../master/src/main/java/com/stevesun/solutions/_355.java)| O(n)|O(n) | Medium| Design, HashMap, Heap
152153
|353|[Design Snake Game](https://leetcode.com/problems/design-snake-game/)|[Solution](../master/src/main/java/com/stevesun/solutions/DesignSnakeGame.java)| O(?)|O(?) | Medium|
153154
|351|[Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/)|[Solution](../master/src/main/java/com/stevesun/solutions/AndroidUnlockPatterns.java)| O(?)|O(?) | Medium|
154155
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)|[Solution](../master/src/main/java/com/stevesun/solutions/IntersectionOfTwoArraysII.java)| O(m+n)|O((m+n)) could be optimized | Easy| HashMap, Binary Search
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
package com.stevesun.solutions;
2+
3+
import java.util.*;
4+
5+
/**
6+
* 355. Design Twitter
7+
*
8+
* Design a simplified version of Twitter where users can post tweets,
9+
* 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:
10+
postTweet(userId, tweetId): Compose a new tweet.
11+
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.
12+
follow(followerId, followeeId): Follower follows a followee.
13+
unfollow(followerId, followeeId): Follower unfollows a followee.
14+
15+
Example:
16+
17+
Twitter twitter = new Twitter();
18+
19+
// User 1 posts a new tweet (id = 5).
20+
twitter.postTweet(1, 5);
21+
22+
// User 1's news feed should return a list with 1 tweet id -> [5].
23+
twitter.getNewsFeed(1);
24+
25+
// User 1 follows user 2.
26+
twitter.follow(1, 2);
27+
28+
// User 2 posts a new tweet (id = 6).
29+
twitter.postTweet(2, 6);
30+
31+
// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
32+
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
33+
twitter.getNewsFeed(1);
34+
35+
// User 1 unfollows user 2.
36+
twitter.unfollow(1, 2);
37+
38+
// User 1's news feed should return a list with 1 tweet id -> [5],
39+
// since user 1 is no longer following user 2.
40+
twitter.getNewsFeed(1);
41+
*/
42+
public class _355 {
43+
//credit: https://discuss.leetcode.com/topic/48100/java-oo-design-with-most-efficient-function-getnewsfeed
44+
public static class Twitter {
45+
46+
private static int timestamp = 0;
47+
private Map<Integer, User> map;
48+
49+
class Tweet {
50+
public int time;
51+
public int id;
52+
public Tweet next;//have a pointer, so we could be more memory efficient when retrieving tweets, think about merging k sorted lists
53+
54+
public Tweet(int id) {
55+
this.id = id;
56+
time = timestamp++;
57+
next = null;
58+
}
59+
}
60+
61+
//the meat part of this OO design, have a User object itself, have follow() and unfollow() method embedded inside it
62+
class User {
63+
public int id;
64+
public Set<Integer> followed;
65+
public Tweet tweetHead;
66+
67+
public User(int id) {
68+
this.id = id;
69+
followed = new HashSet<>();
70+
followed.add(id);//followe itself first
71+
this.tweetHead = null;
72+
}
73+
74+
public void follow(int followeeId) {
75+
followed.add(followeeId);
76+
}
77+
78+
public void unfollow(int followeeId) {
79+
followed.remove(followeeId);
80+
}
81+
82+
public void postTweet(int tweetId) {
83+
//every time we post, we prepend it to the head of the tweet
84+
Tweet head = new Tweet(tweetId);
85+
head.next = tweetHead;
86+
tweetHead = head;//don't forget to overwrite tweetHead with the new head
87+
}
88+
}
89+
90+
/** Initialize your data structure here. */
91+
public Twitter() {
92+
map = new HashMap<>();
93+
}
94+
95+
/** Compose a new tweet. */
96+
public void postTweet(int userId, int tweetId) {
97+
//update oneself newsFeed and also all of his followers' newsFeed
98+
if (!map.containsKey(userId)) {
99+
User user = new User(userId);
100+
map.put(userId, user);
101+
}
102+
User user = map.get(userId);
103+
user.postTweet(tweetId);
104+
}
105+
106+
/** 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. */
107+
public List<Integer> getNewsFeed(int userId) {
108+
List<Integer> newsFeed = new LinkedList<>();
109+
if (!map.containsKey(userId)) return newsFeed;
110+
Set<Integer> users = map.get(userId).followed;
111+
PriorityQueue<Tweet> heap = new PriorityQueue<>(users.size(), (a, b) -> b.time - a.time);
112+
for (int user : users) {
113+
Tweet tweet = map.get(user).tweetHead;
114+
//it's super important to check null before putting into the heap
115+
if (tweet != null) {
116+
heap.offer(tweet);
117+
}
118+
}
119+
120+
int count = 0;
121+
while (!heap.isEmpty() && count < 10) {
122+
Tweet tweet = heap.poll();
123+
newsFeed.add(tweet.id);
124+
count++;
125+
if (tweet.next != null) {
126+
heap.offer(tweet.next);
127+
}
128+
}
129+
130+
return newsFeed;
131+
}
132+
133+
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
134+
public void follow(int followerId, int followeeId) {
135+
if (!map.containsKey(followeeId)) {
136+
User user = new User(followeeId);
137+
map.put(followeeId, user);
138+
}
139+
140+
if (!map.containsKey(followerId)) {
141+
User user = new User(followerId);
142+
map.put(followerId, user);
143+
}
144+
145+
map.get(followerId).follow(followeeId);
146+
}
147+
148+
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
149+
public void unfollow(int followerId, int followeeId) {
150+
if (!map.containsKey(followerId) || followeeId == followerId) return;
151+
map.get(followerId).unfollow(followeeId);
152+
}
153+
}
154+
155+
/**
156+
* Your Twitter object will be instantiated and called as such:
157+
* Twitter obj = new Twitter();
158+
* obj.postTweet(userId,tweetId);
159+
* List<Integer> param_2 = obj.getNewsFeed(userId);
160+
* obj.follow(followerId,followeeId);
161+
* obj.unfollow(followerId,followeeId);
162+
*/
163+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.stevesun;
2+
3+
import com.stevesun.solutions._355;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import java.util.List;
8+
9+
import static org.junit.Assert.assertEquals;
10+
11+
/**
12+
* Created by stevesun on 5/10/17.
13+
*/
14+
public class _355Test {
15+
private static _355.Twitter twitter ;
16+
17+
@BeforeClass
18+
public static void setup() {
19+
twitter = new _355.Twitter();
20+
}
21+
22+
@Test
23+
public void test1(){
24+
twitter.postTweet(1, 5);
25+
List<Integer> user1newsFeed = twitter.getNewsFeed(1);
26+
assertEquals(1, user1newsFeed.size());
27+
assertEquals(5, (int) user1newsFeed.get(0));
28+
29+
twitter.follow(1, 2);
30+
twitter.postTweet(2, 6);
31+
user1newsFeed = twitter.getNewsFeed(1);
32+
assertEquals(2, user1newsFeed.size());
33+
assertEquals(6, (int) user1newsFeed.get(0));
34+
assertEquals(5, (int) user1newsFeed.get(1));
35+
36+
twitter.unfollow(1, 2);
37+
user1newsFeed = twitter.getNewsFeed(1);
38+
assertEquals(1, user1newsFeed.size());
39+
}
40+
}

0 commit comments

Comments
 (0)