当前位置:   article > 正文

C语言 | Leetcode C语言题解之第332题重新安排行程

C语言 | Leetcode C语言题解之第332题重新安排行程

题目:

题解:

  1. char* id2str[26 * 26 * 26];
  2. int str2id(char* a) {
  3. int ret = 0;
  4. for (int i = 0; i < 3; i++) {
  5. ret = ret * 26 + a[i] - 'A';
  6. }
  7. return ret;
  8. }
  9. int cmp(const void* _a, const void* _b) {
  10. int **a = (int**)_a, **b = (int**)_b;
  11. return (*b)[0] - (*a)[0] ? (*b)[0] - (*a)[0] : (*b)[1] - (*a)[1];
  12. }
  13. int* vec[26 * 26 * 26];
  14. int vec_len[26 * 26 * 26];
  15. int* stk;
  16. int stk_len;
  17. void dfs(int curr) {
  18. while (vec_len[curr] > 0) {
  19. int tmp = vec[curr][--vec_len[curr]];
  20. dfs(tmp);
  21. }
  22. stk[stk_len++] = curr;
  23. }
  24. char** findItinerary(char*** tickets, int ticketsSize, int* ticketsColSize, int* returnSize) {
  25. memset(vec_len, 0, sizeof(vec_len));
  26. stk = malloc(sizeof(int) * (ticketsSize + 1));
  27. stk_len = 0;
  28. int* tickets_tmp[ticketsSize];
  29. for (int i = 0; i < ticketsSize; i++) {
  30. tickets_tmp[i] = (int*)malloc(sizeof(int) * 2);
  31. tickets_tmp[i][0] = str2id(tickets[i][0]);
  32. tickets_tmp[i][1] = str2id(tickets[i][1]);
  33. id2str[tickets_tmp[i][0]] = tickets[i][0];
  34. id2str[tickets_tmp[i][1]] = tickets[i][1];
  35. }
  36. qsort(tickets_tmp, ticketsSize, sizeof(int*), cmp);
  37. int add = 0;
  38. while (add < ticketsSize) {
  39. int adds = add + 1, start = tickets_tmp[add][0];
  40. while (adds < ticketsSize && start == tickets_tmp[adds][0]) {
  41. adds++;
  42. }
  43. vec_len[start] = adds - add;
  44. vec[start] = malloc(sizeof(int) * vec_len[start]);
  45. for (int i = add; i < adds; i++) {
  46. vec[start][i - add] = tickets_tmp[i][1];
  47. }
  48. add = adds;
  49. }
  50. dfs(str2id("JFK"));
  51. *returnSize = ticketsSize + 1;
  52. char** ret = malloc(sizeof(char*) * (ticketsSize + 1));
  53. for (int i = 0; i <= ticketsSize; i++) {
  54. ret[ticketsSize - i] = id2str[stk[i]];
  55. }
  56. return ret;
  57. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/980394
推荐阅读
相关标签
  

闽ICP备14008679号