355. Design Twitter \ 378. Kth Smallest Element in a Sorted Matrix

355. Design Twitter

题目描述

Design a simplified version of Twitter where users can post tweets, 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:

  • postTweet(userId, tweetId): Compose a new tweet.
  • 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.
  • follow(followerId, followeeId): Follower follows a followee.
  • unfollow(followerId, followeeId): Follower unfollows a followee.
Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

代码实现

这种方法排名50%。

class Twitter {
private:
    map<int, vector<int>> user_database; // follow map
    vector<pair<int, int>> post2user;    // 
public:
    /** Initialize your data structure here. */
    Twitter() {

    }

    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        post2user.push_back(make_pair(userId, 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. */
    vector<int> getNewsFeed(int userId) {
        int p_len = post2user.size();
        vector<int> res;
        int f_len = user_database[userId].size();
        int count = 0;
        for(vector<pair<int, int>>::reverse_iterator it = post2user.rbegin(); it != post2user.rend(); it++) {
            if(count == 10) break;
            if(it->first == userId) {res.push_back(it->second); count++;}
            else {
                for(auto i:user_database[userId])
                    if(i == it->first) {
                        res.push_back(it->second);
                        count++;
                        break;
                    }
            }
        }

        return res;
    }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        user_database[followerId].push_back(followeeId);
    }

    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        int f_len = user_database[followerId].size();
        for(int i = 0; i < f_len; i++) {
            if(user_database[followerId][i] == followeeId) {
                user_database[followerId].erase(user_database[followerId].begin() + i);
                break;
            }    
        }
    }
};

/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postTweet(userId,tweetId);
 * vector<int> param_2 = obj.getNewsFeed(userId);
 * obj.follow(followerId,followeeId);
 * obj.unfollow(followerId,followeeId);
 */

378. Kth Smallest Element in a Sorted Matrix

这道题目我是用归并排序来求得。

题目描述

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note:
You may assume k is always valid, 1 ≤ k ≤ n2 .

代码实现

这种做法可以击败50%的代码。

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int row = matrix.size();
        int col = matrix[0].size();
        vector<int> ind(row);
        int res = INT_MAX;
        while(k) {
            res = INT_MAX;
            int rec = 0;
            for(int i = 0; i < row; i++) {
                if(ind[i] < col && matrix[i][ind[i]] < res) {
                    res = matrix[i][ind[i]];
                    rec = i;
                }
            }
            ind[rec]++;
            k--;
        }

        return res;
    }
};

当然这里的思路可以使用队列来做,这里使用一种叫做优先级队列的东西,就是会根据自定义的优先级进行插入。

class Solution {
public:
    struct compare
    {
        bool operator()(const pair<int,pair<int, int> >& a, const pair<int,pair<int, int> >& b) {
            return a.first>b.first;
        }
    };

    int kthSmallest(vector<vector<int>>& arr, int k) {
        int n=arr.size(),m=arr[0].size();
        priority_queue< pair<int,pair<int, int> >, vector<pair<int, pair<int, int> > >, compare > p;
        for(int i=0;i<n;i++)  p.push(make_pair(arr[i][0],make_pair(i,0)));
        int x=k,ans;
        while(x--) {
            int e=p.top().first;
            int i=p.top().second.first;
            int j=p.top().second.second;
            ans=e; p.pop();
            if(j!=m-1) p.push(make_pair(arr[i][j+1],make_pair(i,j+1)));
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值