剑指offer[31、49]

本文解析了剑指Offer中的两道经典算法题:栈的压入、弹出序列及求第n个丑数。详细介绍了如何利用栈进行序列验证及动态规划解决丑数问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

剑指 Offer 31. 栈的压入、弹出序列

题目

在这里插入图片描述

思路

本题比较简单。借助一个栈对着push和pop数据执行,如果返回的栈为空,则说明可以顺利执行,否则不能通过。
首先将push中的数组压入栈中,之后验证是否与pop数组中的数字相同,如果相同循环弹出栈(同时满足栈不为空),直到pop数组中的数字与栈顶不同,则继续将push数组中下一个数字循环上方操作。

代码

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> res=new Stack<>();
        int j=0;
        for(int i=0;i<pushed.length;i++){
            res.push(pushed[i]);
            // 注意下列循环判定中应该使用res.peek()与popped[j]比较,因为可能存在连续的pop,仅使用pushed[i]是错误的!!!
            while(!res.isEmpty()&&res.peek()==popped[j]){
                res.pop();
                j++;
            }
        }
        return res.isEmpty();
    }
}
class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        res=[]
        j=0
        for push in pushed:
            res.append(push)
            while res and res[-1]==popped[j]:
                res.pop()
                j+=1
        return not res

剑指 Offer 49. 丑数

题目

在这里插入图片描述

分析

在这里插入图片描述

代码

class Solution {
    public int nthUglyNumber(int n) {
        int[] dp=new int[n];
        int a=0,b=0,c=0;
        dp[0]=1;
        // 注意循环从i=1开始,默认dp[0]=1
        for(int i=1;i<n;i++){
            int n2,n3,n5;
            n2=dp[a]*2;
            n3=dp[b]*3;
            n5=dp[c]*5;
            dp[i]=Math.min(Math.min(n2,n3),n5);
            if(n2==dp[i]) a++;
            if(n3==dp[i]) b++;
            if(n5==dp[i]) c++;
        }
        return dp[n-1];

    }
}
class Solution:
    def nthUglyNumber(self, n: int) -> int:
        dp,a,b,c=[1]*n,0,0,0
        for i in range(1,n):
            n2,n3,n5=dp[a]*2,dp[b]*3,dp[c]*5
            dp[i]=min(n2,n3,n5)
            if n2==dp[i]:a+=1
            if n3==dp[i]:b+=1
            if n5==dp[i]:c+=1
        return dp[-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值