当前位置:网站首页>剑指 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];
}
}
边栏推荐
猜你喜欢
STM32单片机LORA无线远程火灾报警监控系统DS18B20MQ2火焰检测
LeetCode 94.二叉树的中序遍历(简单)
LeetCode 1894. Find the student number that needs to be supplemented with chalk
LeetCode 1720. Decoding XORed Arrays (Simple)
开源游戏服务器框架NoahGameFrame(NF)客户端环境搭建(三)
Pytorch - 07. Multidimensional characteristics of input processing
序列化、编码、requests库json和data参数
每日刷题(day02)——leetcode 622. 设计循环队列
Pico设备中的截图以及视频文件通过adb命令保存到电脑中
以STM32F103C6T6为例通过配置CubeMX实现EXIT外部中断
随机推荐
LeetCode refers to offer 10-I. Fibonacci sequence (simple)
Collection set interface
【fiddler4】使用fiddler设置简单并发
离散数学的学习记录
I don't like my code
LeetCode 162.寻找峰值(中等)
Notes for RNN
pytorch-10.卷积神经网络
详解 Hough 变换(下)圆形检测
pytorch-09.多分类问题
Unity中Xml简介以及通过脚本读取Xml文本中的内容
generic notes()()()
接口自动化2.0
Pytorch - 07. Multidimensional characteristics of input processing
Common class String overview
钴镍回收树脂的工艺原理
通过adb devices命令在控制台显示企业级PicoNeo3设备号
Explain the principle of MySql index in detail
LeetCode 94.二叉树的中序遍历(简单)
51单片机ST188手持人体温度脉搏心率测量仪锂电池充电