当前位置:网站首页>剑指 Offer(第 2 版)7/5 5-8
剑指 Offer(第 2 版)7/5 5-8
2022-08-10 05:36:00 【吉良吉影__.】
1.剑指 Offer 06. 从尾到头打印链表 简单
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public int[] reversePrint(ListNode head) {
int n = 0;
ListNode temp = head;
//统计链表节点个数
while (temp != null){
n++;
temp = temp.next;
}
int[] res = new int[n];
while (head != null){
res[--n] = head.val;
head = head.next;
}
return res;
}
}
2.剑指 Offer 09. 用两个栈实现队列 简单
//两个栈实现队列
class CQueue {
Stack<Integer> stack = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public CQueue() {
}
public void appendTail(int value) {
stack.push(value);
}
public int deleteHead() {
//两个栈都空,表示此时队列中元素个数为0
if (stack.isEmpty() && stack2.isEmpty())return -1;
if (!stack2.isEmpty())return stack2.pop();//栈2有元素则直接返回
while (!stack.isEmpty())stack2.push(stack.pop());//转移
if (!stack2.isEmpty())return stack2.pop();//栈2有元素则返回
return -1;
}
}
/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
3.剑指 Offer 10- I. 斐波那契数列 简单
注意,要在循环中取模,不能等到循环结束再取模,防止越界错误
斐波那契数列
class Solution {
public int fib(int n) {
if (n < 2)return n;
int a = 0;
int b = 1;
int c = 0;
for (int i = 2; i <= n; i++) {
//必须在这里提前取模
c = a + b > 1000000007 ? (a + b) % 1000000007 : a + b;
a = b;
b = c;
}
//不能前面没有取模,直接在这里取模,否则前面循环中可能越界
return c;
}
}
4.剑指 Offer 10- II. 青蛙跳台阶问题 简单
注意,要在循环中取模,不能等到循环结束再取模,防止越界错误
斐波那契数列
class Solution {
public int numWays(int n) {
if (n == 0)return 1;//第0阶有1种方案
if (n < 3)return n;
//dp[i] = 跳到第i阶台阶的方案数
int[] dp = new int[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = (dp[i - 1] + dp[i - 2]) % 1000000007;
}
return dp[n];
}
}
边栏推荐
猜你喜欢

在Unity中利用代码动态更改场景中的天空盒

STM32单片机RGB红蓝调光植物补光系统红光蓝光PWM调色调节亮度

Pytorch配置与实战--Tips

离散数学的学习记录

ASP.NET连接SQL Server的步骤

The way for programmers to make money from a sideline business and increase their monthly income by 20K

Test of the opposite sex what you look like?

Likou - Number of Provinces

pytorch-10. Convolutional Neural Networks

51单片机智能远程遥控温控PWM电风扇系统红外遥控温度速度定时关机
随机推荐
Likou - Number of Provinces
pytorch-11.卷积神经网络(高级篇)
Unity中实现Animation Clip动画片段的倒播(该案例可以防止动画延迟)
STM32单片机手机APP蓝牙高亮RGB彩灯控制板任意颜色亮度调光
STM32单片机OLED俄罗斯方块单片机小游戏
过大数组导致爆栈的解决方法记录(堆栈)
51单片机营养液自动配置搅拌系统TDS浓度采集自动加水加营养液
The way for programmers to make money from a sideline business and increase their monthly income by 20K
ASP.NET有关于文件上传、下载、全选、删除选中重要干货(亲测有效)
基于MNIST数据集的简单FC复现
pytorch-10.卷积神经网络(作业)
Tensorflow 2.0 使用流程详解
pytorch-05. Implementing linear regression with pytorch
pytorch-05.用pytorch实现线性回归
中间件-Rocktmq
(Flutter报错)Cannot run with sound null safety, because the following dependencies
在Unity中让物体围绕自身的x、y、z轴进行旋转(亲测有效)
Unity中采用二进制存档与读档
51单片机AD590温度测量ADC0832运放2.73V减法电压变换
51单片机BH1750智能补光灯台灯光强光照恒流源LED控制系统