タイトル説明
これで、特別な形式の野球ゲームのレコーダーになりました。このゲームはいくつかのラウンドで構成されており、過去数ラウンドの得点が次の数ラウンドの得点に影響を与える可能性があります。
ゲームが始まったとき、記録は空白でした。操作を記録する文字列リストopsを取得します。ここで、ops [i]は記録する必要のあるi番目の操作であり、opsは次のルールに従います。
- 整数x-このラウンドで取得された新しいスコアxを表します
- 「+」-このラウンドで取得された新しいスコアが、前の2つのスコアの合計であることを示します。アイテムデータは、この操作が記録される前に常に2つの有効なスコアがあることを保証します。
- 「D」-このラウンドで取得された新しいスコアが前のスコアの2倍であることを示します。アイテムデータは、この操作のレコードの前に常に有効なスコアがあることを保証します。
- 「C」-前のスコアが無効であり、レコードから削除されていることを示します。アイテムデータは、この操作のレコードの前に常に有効なスコアがあることを保証します。
レコード内のすべてのスコアの合計を返してください。
出典:LeetCode(LeetCode)
リンク:https://leetcode-cn.com/problems/baseball-game
著作権はLeetCodeが所有しています。商用転載の場合は、公認機関にご連絡ください。非商用転載の場合は、出典を明記してください。
回答
- 解決策1
時間がかかるif判定文を使用する
int calPoints(char ** ops, int opsSize){
int score[1000];
int top=-1;
int sum=0;
for(int i=0;i<opsSize;i++)
{
if(ops[i][0]=='C')
{
top--;
}
else if(ops[i][0]=='D')
{
top++;
score[top]=score[top-1]*2;
}
else if(ops[i][0]=='+')
{
top++;
score[top]=score[top-1]+score[top-2];
}
else
{
top++;
score[top]=0;
if(ops[i][0]=='-')
{
for(int j=1;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]-=(int)ops[i][j]-48;
}
}
else
{
for(int j=0;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]+=(int)ops[i][j]-48;
}
}
}
}
for(int i=0;i<=top;i++)
{
sum+=score[i];
}
return sum;
}
スイッチの使用を改善し、時間を短縮します
int calPoints(char ** ops, int opsSize){
int score[1000];
int top=-1;
int sum=0;
for(int i=0;i<opsSize;i++)
{
switch (ops[i][0])
{
case 'C':
top--;
break;
case 'D':
top++;
score[top]=score[top-1]*2;
break;
case '+':
top++;
score[top]=score[top-1]+score[top-2];
break;
default:
top++;
score[top]=0;
if(ops[i][0]=='-')
{
for(int j=1;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]-=(int)ops[i][j]-48;
}
}
else
{
for(int j=0;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]+=(int)ops[i][j]-48;
}
}
break;
}
}
for(int i=0;i<=top;i++)
{
sum+=score[i];
}
return sum;
}
- 改善2
- C言語ライブラリ関数atoiを使用して、文字列整数を整数整数に変換すると、使用されるスペースがわずかに増加します。
- malloc関数を使用して、文字列の長さに応じてメモリを割り当てます
int calPoints(char ** ops, int opsSize){
int* score=(int *)malloc(opsSize*sizeof(int));
int top=-1;
int sum=0;
for(int i=0;i<opsSize;i++)
{
switch (ops[i][0])
{
case 'C':
top--;
break;
case 'D':
top++;
score[top]=score[top-1]*2;
break;
case '+':
top++;
score[top]=score[top-1]+score[top-2];
break;
default:
top++;
score[top]=atoi(ops[i]);
break;
}
}
for(int i=0;i<=top;i++)
{
sum+=score[i];
}
return sum;
}