leetcode每日一题 1441. 用栈操作构建数组

1441. 用栈操作构建数组

难度中等

给你一个数组 target 和一个整数 n。每次迭代,需要从  list = { 1 , 2 , 3 ..., n } 中依次读取一个数字。

请使用下述操作来构建目标数组 target :

  • "Push":从 list 中读取一个新元素, 并将其推入数组中。
  • "Pop":删除数组中的最后一个元素。
  • 如果目标数组构建完成,就停止读取更多元素。

题目数据保证目标数组严格递增,并且只包含 1 到 n 之间的数字。

请返回构建目标数组所用的操作序列。如果存在多个可行方案,返回任一即可。

示例 1:

输入:target = [1,3], n = 3
输出:["Push","Push","Pop","Push"]
解释: 
读取 1 并自动推入数组 -> [1]
读取 2 并自动推入数组,然后删除它 -> [1]
读取 3 并自动推入数组 -> [1,3]

示例 2:

输入:target = [1,2,3], n = 3
输出:["Push","Push","Push"]

示例 3:

输入:target = [1,2], n = 4
输出:["Push","Push"]
解释:只需要读取前 2 个数字就可以停止。

提示:

  • 1 <= target.length <= 100
  • 1 <= n <= 100
  • 1 <= target[i] <= n
  • target 严格递增

分析:这肯定不是中等题,我都会。target数组严格递增,list数组从1到n,那直接从1开始遍历到n。判断第 i 个元素是否在target数组里,若存在 "Push", 不存在 "Push" "Pop"。

class Solution {
    public List<String> buildArray(int[] target, int n) {

        List<String> list = new ArrayList<String>();
        Set<Integer> set = new HashSet<Integer>();

        // 数组转Set
        for (int t : target){
            set.add(t);
        }

        for (int i = 1; i <= n; i++){
            if (set.contains(i)){   // 存在
                list.add("Push");
            }else{                  // 不存在
                list.add("Push");
                list.add("Pop");
            }
        }

        return list;
    }
}

执行代码!测试用例!没问题,提交!错了,没有考虑 target 数组的值比 n 小。

小问题,n改为target目标数字最大值 target[target.length - 1]。重新运行错误用例,OK可以!再次提交,过了!

class Solution {
    public List<String> buildArray(int[] target, int n) {

        List<String> list = new ArrayList<String>();
        Set<Integer> set = new HashSet<Integer>();

        // 数组转Set
        for (int t : target){
            set.add(t);
        }

        for (int i = 1; i <= target[target.length - 1]; i++){
            if (set.contains(i)){   // 存在
                list.add("Push");
            }else{                  // 不存在
                list.add("Push");
                list.add("Pop");
            }
        }

        return list;
    }
}

执行结果:

通过

显示详情

添加备注

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:41.3 MB, 在所有 Java 提交中击败了72.31%的用户

通过测试用例:49 / 49

 让我看看题解,哇!三叶姐已经发了题解,优秀!优雅,实在是太优雅了!

分析:从 1 到 n 开始遍历值,指针 j 指向 target 数组,每次遍历都 "Push",只有当 target[ j ] != i 时才 "Pop",否则 j++后移。

class Solution {
    public List<String> buildArray(int[] target, int n) {

        List<String> list = new ArrayList<String>();
        int len = target.length;

        for (int i = 1, j = 0; i <= n && j < len ; i++){
            list.add("Push");   // 压栈

            if (target[j] != i){    // 栈顶元素和 i 是否相同
                list.add("Pop");// 出栈
            }else {
                j++;
            }
        }
        return list;
    }
}

这转啥Set啊,栈操作模拟数组!是我太菜了- -

执行结果:

通过

显示详情

添加备注

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:41.3 MB, 在所有 Java 提交中击败了68.01%的用户

通过测试用例:49 / 49

宫水三叶 : 简单模拟题 1441. 用栈操作构建数组 

猜你喜欢

转载自blog.csdn.net/qq_43833393/article/details/127331173