TreeviewCopyright © aleen42 all right reserved, powered by aleen42

1441. 用栈操作构建数组

https://leetcode-cn.com/problems/build-an-array-with-stack-operations/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-09-01 20:10:12
 * @LastEditTime: 2020-09-01 20:10:32
 * @Description: https://leetcode-cn.com/problems/build-an-array-with-stack-operations/
 * @FilePath: \leetcode-googtech\#1441. Build an Array With Stack Operations\Solution.java
 * @WebSite: https://algorithm.show/
 */

class Solution {
    public List<String> buildArray(int[] target, int n) {
        // 初始化结果列表
        List<String> result = new LinkedList<>();
        // 初始化数组下标
        int i = 0;
        // 遍历 1 到 N 之间所有的数值
        for(int j = 1; j <= n; j++) {
            // 若当前数组下标与数组长度值相同则跳出并结束循环
            if(i == target.length) {
                break;
            }
            // 若当前下标所指的数组元素与当前 j 值相同,
            // 则将 Push 字符存储到结果列表中,并向后移动数组元素指针
            if(target[i] == j) {
                result.add("Push");
                i++;
            // 反之则说明数组中缺失当前数值 j
            }else {
                result.add("Push");
                result.add("Pop");
            }
        }
        // 返回结果列表
        return result;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-09-01 20:10:17
LastEditTime: 2020-09-01 20:10:39
Description: https://leetcode-cn.com/problems/build-an-array-with-stack-operations/
FilePath: \leetcode-googtech\#1441. Build an Array With Stack Operations\Solution.py
WebSite: https://algorithm.show/
'''

class Solution(object):
    def buildArray(self, target, n):
        """
        :type target: List[int]
        :type n: int
        :rtype: List[str]
        """
        # 初始化结果列表
        result = []
        # 遍历 1 到 n 之间所有的数值
        for num in range(1, target[-1] + 1):
            # 将 Push 字符存储到结果列表中
            result.append('Push')
            # 若当前数值 num 在数组 target 不存在,则说明数组中缺失数值 num
            if num not in target:
                # 进而将 Pop 字符添加到结果列表中
                result.append('Pop')
        # 返回结果列表
        return result
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""