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;
}
相关推荐
Norvyn_718 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
呆呆的小鳄鱼1 小时前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香1 小时前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely1 小时前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07121 小时前
自学力扣:最长连续序列
数据结构·算法·leetcode
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
棐木9 小时前
【C语言】动态内存管理
c语言·free·malloc·realloc·calloc·动态内存
好易学·数据结构10 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
墨染点香12 小时前
LeetCode Hot100【5. 最长回文子串】
算法·leetcode·职场和发展