【问题标题】:A c solution for leetcode 38 count and say confuse meleetcode 38 的一个 c 解决方案 count and say 迷惑我
【发布时间】:2018-04-25 16:03:13
【问题描述】:

这是问题count and say 我在下面的接受代码。我写了main函数,提交的时候复制countAndSay函数。

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

char* countAndSay(int n) 
{
    if( n == 1 ) 
        return "1";
    char *cur = (char *)malloc(2*sizeof(char));
    char *res;
    cur[0]='1';
    cur[1]='\0';

    int len, idx, j, count;
    for(int i = 2; i <= n; ++i)
    {
       len = strlen(cur);
       res = (char *)malloc(len * 2 + 1);
       memset(res, '\0', len * 2 + 1);
       count = 1;
       for(idx = 1, j = 0; idx < len; ++idx)
       {
          if(cur[idx] == cur[idx-1])
          {
             ++count;
          }
          else
          {
             res[j++] = '0' + count;
             res[j++] = cur[idx-1];
             count = 1;
          }
       }//end of for

       res[j++] = '0' + count;
       res[j++] = cur[len-1];
       free(cur);
       cur = res;
    }   
    return cur;
}

int main()
{
   char *s = countAndSay(INT_MAX);
   printf("%s\n",s);
   free(s); 
   return 0;
}

我从讨论部分和修改部分看到的这段代码。我只是困惑 为什么使用 res[j++] = '0' + count 因为 count 可能是 11 或 12,当 count 大于 9 时,res[j++] 不是 '0' 和 '9' 之间的字符,所以我运行了代码,并且它出错了。

ctci(1720,0x100392380) malloc: * mach_vm_map(size=18446744071713468416) 失败(错误代码=3) * 错误:无法分配区域 *** 在 malloc_error_break 中设置断点进行调试 程序以退出代码结束:9

我猜可能是系列太长了,我的电脑内存不够,所以我把num改成了500,还是出错了。

就是不知道为什么。

按照@WhozCraig 的建议,我将 len 打印到 malloc,结果如下。

1
2
2
4
6
6
8
10
14
20
26
34
46
62
78
102
134
176
226
302
408
528
678
904
1182
1540
2012
2606
3410
4462
5808
7586
9898
12884
16774
21890
28528
37158
48410
63138
82350
107312
139984
182376
237746
310036
403966
526646
686646
894810
1166642
1520986
1982710
2584304
3369156
4391702
5724486
7462860
9727930
12680852
16530884
21549544
28091184
36619162
47736936
62226614
81117366
105745224
137842560
179691598
234241786
305351794
398049970
518891358
676414798
881752750
1149440192
ctci(1828,0x100392380) malloc: *** mach_vm_map(size=18446744071713468416) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Program ended with exit code: 9

所以 1149440192B ,1149440192/(1024*1024)MB=1096MB,我只看剩余的内存,它大于 1096.1915893555MB。

【问题讨论】:

  • 我认为你最好将printf("i=%d, len=%d\n", i, len); 放在循环顶部,紧跟在(不必要的)strlen 调用之后。你会惊讶于它使用了多少内存,以及它使用它的速度。有些东西告诉我你的算法有……问题。
  • @WhozCraig 谢谢你的建议,我明天会看到这个,已经很晚了,现在必须睡觉了。再次感谢。
  • 不要转换从malloc()返回的值。如果您在范围内有正确的原型,则演员表是无用的;如果您在范围内没有正确的原型,则强制转换可能会消除编译器可能提供的任何有用的警告。

标签: c


【解决方案1】:

你的内存用完了。

循环for(int i = 2; i &lt;= n; ++i) 的每一次传递都可能使res 的大小翻倍,而您使用n == INT_MAX 调用它。世界上没有计算机可以分配1&lt;&lt;INT_MAX 字节的 RAM。

问题陈述说为n == 30 运行。您的输出表明有足够的 RAM 可以运行 30 次。

【讨论】:

    猜你喜欢
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多