C语言 | Leetcode C语言题解之第355题设计推特

题目:

题解:

cpp 复制代码
typedef struct {
    int tweetId;
    int userId;
} Tweet;

typedef struct {
    int* dict[501];
    Tweet* tweetList;
    int tweetListLen;
} Twitter;

Twitter* twitterCreate() {
    Twitter* obj = malloc(sizeof(Twitter));
    for (int i = 0; i < 501; i++) {
        obj->dict[i] = calloc(501, sizeof(int));
        obj->dict[i][i] = 1;
    }
    obj->tweetList = malloc(30000 * sizeof(Tweet));
    obj->tweetListLen = 0;
    return obj;
}

void twitterPostTweet(Twitter* obj, int userId, int tweetId) {
    obj->tweetList[obj->tweetListLen].tweetId = tweetId;
    obj->tweetList[obj->tweetListLen].userId = userId;
    obj->tweetListLen++;
    return;
}

int* twitterGetNewsFeed(Twitter* obj, int userId, int* retSize) {
    int* res = malloc(10 * sizeof(int));
    *retSize = 0;
    for (int i = obj->tweetListLen - 1; i >= 0; i--) {
        if (obj->dict[userId][obj->tweetList[i].userId] == 1) {
            res[*retSize] = obj->tweetList[i].tweetId;
            (*retSize)++;
        }
        if (*retSize == 10) {
            break;
        }
    }
    return res;
}

void twitterFollow(Twitter* obj, int followerId, int followeeId) {
    obj->dict[followerId][followeeId] = 1;
    return;
}

void twitterUnfollow(Twitter* obj, int followerId, int followeeId) {
    obj->dict[followerId][followeeId] = 0;
    return;
}

void twitterFree(Twitter* obj) {
    for (int i = 0; i < 501; i++) {
        free(obj->dict[i]);
    }
    free(obj->tweetList);
    free(obj);
    return;
}
相关推荐
RuoZoe7 小时前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_4 天前
C语言内存函数
c语言·后端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll5 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐5 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶5 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode