LeetCode·每日一题·1441.用栈操作构建数组·栈模拟

链接: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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值