2024年8月6日 星期二

[1441] Build an Array With Stack Operations

寫了一個初版覺得充滿贅步?! XD 放在最後面~

改進版: 
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char** buildArray(int* target, int targetSize, int n, int* returnSize) {
int ret_idx = 0;
int tar_idx = 0;
char** ret = calloc (200, sizeof (char*));
for (int i=1; i<=n; i++)
{
if (tar_idx >= targetSize)
break;

ret[ret_idx]= calloc (5, sizeof(char));
sprintf(ret[ret_idx++], "%s", "Push");
if (target[tar_idx] == i)
tar_idx++;
else
{
ret[ret_idx]= calloc (4, sizeof(char));
sprintf(ret[ret_idx++], "%s", "Pop");
}
}
*returnSize = ret_idx;
return ret;
}

原始版  XD
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char** buildArray(int* target, int targetSize, int n, int* returnSize) {
bool *ret_bool = calloc (targetSize*200, sizeof(bool));// true : push, false:pop
int ret_idx = 0;
int tar_idx = 0;
for (int i=1; i<=n; i++)
{
//printf("%d %d %d\n", i,tar_idx, ret_idx);
if (tar_idx >= targetSize)
break;
if (target[tar_idx] == i)
{
ret_bool[ret_idx++] = true;
tar_idx++;
}
else
{
ret_bool[ret_idx++] = true;
ret_bool[ret_idx++] = false;
}
}
char** ret = calloc (ret_idx, sizeof (char*));
for (int i=0; i<ret_idx; i++)
{
if (ret_bool[i])
{
ret[i]= calloc (5, sizeof(char));
sprintf(ret[i], "%s", "Push");
}
else
{
ret[i]= calloc (4, sizeof(char));
sprintf(ret[i], "%s", "Pop");
}
}
*returnSize = ret_idx;
return ret;
}

沒有留言:

張貼留言