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;
}
相关推荐
XiaoyaoCarter1 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
小狗祈祷诗3 小时前
day22-数据结构之 栈&&队列
c语言·数据结构
AI+程序员在路上4 小时前
XML介绍及常用c及c++库
xml·c语言·c++
软行4 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
How_doyou_do5 小时前
备战菊厂笔试4
python·算法·leetcode
緈福的街口8 小时前
【leetcode】94. 二叉树的中序遍历
算法·leetcode
小刘要努力呀!8 小时前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
草莓熊Lotso8 小时前
【C语言字符函数和字符串函数(一)】--字符分类函数,字符转换函数,strlen,strcpy,strcat函数的使用和模拟实现
c语言·开发语言·经验分享·笔记·其他
小秋学嵌入式-不读研版9 小时前
C42-作业练习
c语言·开发语言·笔记
小羊在奋斗10 小时前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展