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;
}
相关推荐
时间的拾荒人7 小时前
C语言字符函数与字符串函数完全指南
c语言·开发语言
持力行7 小时前
C/C++ 中的 char*:它标识数组吗?为什么能用下标访问?
c语言·c++
小陈的代码之路10 小时前
回文链表(LeetCode 234)C语言最佳解题思路
c语言·leetcode·链表
aaaameliaaa11 小时前
计算斐波那契数(递归、迭代)(1,1,2,3,5.....)
c语言·开发语言·笔记·算法·排序算法
郭梧悠13 小时前
算法:有效的括号
python·算法·leetcode
旖-旎13 小时前
《LeetCode 1137 第N个泰波那契数 和 LeetCode 三步问题》
c++·算法·leetcode·动态规划
wabs66613 小时前
关于动态规划【力扣718.最长重复子数组的思考】
算法·leetcode·动态规划
zhangfeng113314 小时前
算子开发 Overwrite 覆盖/替换模式 Accumulate 累加模式,性能对比 memset错误 bat_alloc 错误
c语言·人工智能·gnu·算子开发
SuperByteMaster14 小时前
JLinkDevices.xml FLM文件路径不对
c语言
LDR00614 小时前
LDR6500赋能POS机底座:单口Type-C供电、维护与产测一体化解决方案
大数据·c语言·人工智能