Sunday, September 3, 2017

355. Design Twitter





 82.10 %
import java.util.concurrent.atomic.AtomicInteger;

class Twitter {
private static AtomicInteger timestamp = new AtomicInteger(0);
// key-user id, value-user object
Map<Integer, User> userMap;
class User {
int userId;
Node sentinel;
Set<Integer> followee;
public User(int userId) {
this.userId = userId;
this.sentinel = new Node(-1, -1);
this.followee = new HashSet<>(Collections.singletonList(userId));
}
public void postTweet(int tweetId) {
Node tweet = new Node(tweetId, timestamp.incrementAndGet());
// insert new tweet after sentinel node
tweet.next = sentinel.next;
sentinel.next = tweet;
}

public void follow(int followeeId) {
followee.add(followeeId);
}
public void unfollow(int followeeId) {
// do nothing if followeeId is not in the followee set
// this method call returns false
if (followeeId != userId) {
followee.remove(followeeId);
}
}

public Node getFirstTweet() {
return sentinel.next;
}
public List<Integer> getNewsFeed() {
PriorityQueue<Node> maxHeap = new PriorityQueue<>(10, (a, b) -> b.postTime - a.postTime);
for (Integer id : followee) {
Node firstTweet = userMap.get(id).getFirstTweet();
if (firstTweet != null) {
maxHeap.add(firstTweet);
}
}
List<Integer> news = new ArrayList<>();
while (!maxHeap.isEmpty() && news.size() < 10) {
Node curr = maxHeap.poll();
news.add(curr.tweetId);
if (curr.next != null) {
maxHeap.add(curr.next);
}
}
return news;
}
}

class Node {
int tweetId;
int postTime;
Node next;
public Node(int tweetId, int postTime) {
this.tweetId = tweetId;
this.postTime = postTime;
}
}

/** Initialize your data structure here. */
public Twitter() {
userMap = new HashMap<>();
}

/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
userMap.putIfAbsent(userId, new User(userId));
userMap.get(userId).postTweet(tweetId);
}

/** 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> news = new ArrayList<>();
User user = userMap.getOrDefault(userId, null);
if (user != null) {
news = user.getNewsFeed();
}
return news;
}

/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
userMap.putIfAbsent(followerId, new User(followerId));
userMap.putIfAbsent(followeeId, new User(followeeId));
userMap.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 (!userMap.containsKey(followerId) || !userMap.containsKey(followeeId)) {
return;
}
userMap.get(followerId).unfollow(followeeId);
}
}





No comments:

Post a Comment