我参加了 CodeSignal 练习考试,并且能够通过 14/16 测试用例来解决这个问题。您将获得一个向量作为输入(整数列表),并且解决方案将很长很长。
最初我只是使用了两个 for 循环的蛮力解决方案,并将当前的 a[i] concat a[j] 添加到运行总数中。但是,我尝试通过使用记忆来优化它。我使用 unordered_map 对检查我是否已经计算了 (i,j) 对,如果已经计算,只需返回缓存的结果。即使进行了优化,我仍然没有通过任何额外的测试用例并收到 14/16 的结果。我缺少什么见解或优化?
我发现了类似的在线问题,但是他们的见解似乎不适用于这个特定问题。
例如:类似问题
题:
给定一个正整数数组a,您的任务是计算每个可能的 concat(a[i], a[j]) 的总和,其中 concat(a[i],a[j]) 是字符串的串联分别表示 a[I] 和 a[j]。
前任:
a = [10,2]
sol = 1344
a[0],a[0] = 1010
a[0],a[1] = 102
a[1],a[0] = 210
a[1],a[1] = 22
sum of above = 1344
Run Code Online (Sandbox Code Playgroud)
代码:
long long concat(int x, int y)
{
string str = to_string(x)+to_string(y);
return stoll(str);
}
long long calculateSum(vector<int> a)
{
unordered_map<pair<int,int>,long long, hash_pair> …Run Code Online (Sandbox Code Playgroud) 我是C++编程的新手.所以我试着运行一些小程序.我正在使用HP-UX,它有一个编译器,其可执行文件名为aCC.
我正在尝试执行一个小程序
#include <iostream.h>
using namespace std;
class myclass {
public:
int i, j, k;
};
int main()
{
myclass a, b;
a.i = 100;
a.j = 4;
a.k = a.i * a.j;
b.k = 12;
cout << a.k << " " << b.k;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时它给了我一个错误:
> aCC temp.cpp
Error 697: "temp.cpp", line 2 # Only namespace names are valid here.
using namespace std;
^^^
Run Code Online (Sandbox Code Playgroud)
究竟是什么问题?是std不是aCC编译器中的命名空间或者aCC有一些严重的缺点?
如果我更改<iostream.h>为<iostream>,我会收到更多错误,如下所示.
>aCC …Run Code Online (Sandbox Code Playgroud) 我想用下面的代码复制字符串,但它没有复制\'\\0\'。
\n\nvoid copyString(char *to, char *from)\n{\n do{\n *to++ = *from++;\n }while(*from);\n}\nint main(void)\n{\n char to[50];\n char from[] = "text2copy";\n copyString(to, from);\n printf("%s", to);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这是代码的输出:
\n\ntext2copy\xc3\x87\xe2\x96\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xe2\x95\x91kvu\xc2\xa1lvu\nRun Code Online (Sandbox Code Playgroud)\n\n每次我重新运行代码时,text2copy 之后的字符都会发生变化,因此while(*from)工作正常,但会复制随机内容而不是 \'\\0\'。
\n\ntext2copy\xc3\x96\xe2\x96\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xe2\x95\x91kvu\xc2\xa1lvu\ntext2copy\xe2\x95\xa8\xe2\x96\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xe2\x95\x91kvu\xc2\xa1lvu\ntext2copy\xe2\x95\xa1\xe2\x96\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xe2\x95\x91kvu\xc2\xa1lvu\n//etc\nRun Code Online (Sandbox Code Playgroud)\n\n为什么会发生这种情况?
\n