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;
}
相关推荐
yuuki2332333 小时前
【数据结构】用顺序表实现通讯录
c语言·数据结构·后端
夏鹏今天学习了吗4 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
还是码字踏实4 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
ad钙奶长高高4 小时前
【C语言】扫雷游戏详解
c语言
轮到我狗叫了6 小时前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
丛雨要玩游戏7 小时前
字符函数和字符串函数
c语言·开发语言·算法
ad钙奶长高高7 小时前
【C语言】初始C语言
c语言·开发语言·算法
侯小啾7 小时前
【17】C语言-gets() 与 fgets() 函数
c语言·开发语言
是苏浙8 小时前
零基础入门C语言之枚举和联合体
c语言·开发语言
熬了夜的程序员9 小时前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展