链接:https://leetcode.cn/problems/build-an-array-with-stack-operations/solutions/1893132/zhan-mo-ni-zhu-shi-chao-ji-xiang-xi-by-x-66ki/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
题意 -> 从 list = { 1 , 2 , 3 ..., n } 中依次读取一个数字构造一个数组 和 target 一模一样,记录比返回构造过程
构造的方法只有两种:
- "Push":从 list 中读取一个新元素, 并将其推入数组中。
- "Pop":删除数组中的最后一个元素。
如果目标数组构建完成,就停止读取更多元素。返回构造成 target 数组的步骤
题目已经说的很明白了,直接根据两个方法使用一个栈来模拟构造过程即可
具体实现看代码,注释超级详细
代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** buildArray(int* target, int targetSize, int n, int* returnSize){
char push[] = "Push";
char pop[] = "Pop";//操作方法
char ** ans = (char **)malloc(sizeof(char *) * 200);
//每个数最多操作2次,数据最大 100,最多操作 200次
*returnSize = 0;
for(int i = 1, j = 0; j < targetSize && i <= n; i++)//枚举操作过程
{
ans[*returnSize] = (char *)malloc(sizeof(char) * 5);
memcpy(ans[*returnSize], push, sizeof(push));
//不管target数组怎么样,当前元素肯定要入栈,因为只能依次取list中的元素
(*returnSize)++;
if(target[j] != i)
//如果栈顶元素和target中的元素不一样,就pop
//继续取剩余元素直到与当前元素相同才枚举target下一个元素
{
ans[*returnSize] = (char *)malloc(sizeof(char) * 5);
memcpy(ans[*returnSize], pop, sizeof(pop));
(*returnSize)++;
}
else
{
j++;
}
}
return ans;
}
作者:小迅要变强
链接:https://leetcode.cn/problems/build-an-array-with-stack-operations/solutions/1893132/zhan-mo-ni-zhu-shi-chao-ji-xiang-xi-by-x-66ki/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。