TypechoJoeTheme

Toasobi的博客

搜索到 47 篇与 的结果 ———
2023-03-14

反转链表(简单)

反转链表(简单)
这道题主要考察递归做法。在本题递归思路中,采用模拟(纸上求解)的方式得出递归的实现代码如下:<div>class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) { return head; } ListNode node = reverseList(head.next); head.next.next = head; //如果此处head是4,则表示在4,5之间加上5指向4的指针 head.next = null; //此处则表示删去4指向5的指针 return node; } }</div>
2023-03-14

剑指offer(第二版)

0 阅读
0 评论
2023年03月14日
0 阅读
0 评论
2023-03-14

链表中倒数第k个节点(简单)

链表中倒数第k个节点(简单)
这道题不难,主要是记录多一个思路:倒数第k个节点可以使用快慢指针来做。快慢指针,先让快指针走k步,然后两个指针同步走,当快指针走到头时,慢指针就是链表倒数第k个节点。代码如下:<div> public ListNode getKthFromEnd(ListNode head, int k) { ListNode frontNode = head, behindNode = head; while (frontNode != null && k > 0) { frontNode = frontNode.next; k--; } while (frontNode != null) { frontNode = frontNode.next; behindNode = behindNode.next; } return behindNode...
2023-03-14

剑指offer(第二版)

0 阅读
0 评论
2023年03月14日
0 阅读
0 评论
2023-03-07

数值的整数次方(中等)

数值的整数次方(中等)
这道题一开始我还想怎么是到中等题,这不一个for循环的事吗?结果提交超时。。。。看来这道题没那么简单。。(不止我一个人)====================方法:快速幂====================如果是在还没看懂,可以假设一个指数然后在纸上推导一下,就是这个道理代码如下:<div> class Solution { public double myPow(double x, int n) { if(n == 1) return x; if(n == 0) return 1.0; if(n == -1) return 1/x; return n > 0 ? quickMul(x,n):1/quickMul(x,n); } public double quickMul(double x,int n){ if(n == 0) return...
2023-03-07

剑指offer(第二版)

0 阅读
0 评论
2023年03月07日
0 阅读
0 评论
2023-03-07

二进制中1的个数(简单)

二进制中1的个数(简单)
本题我的解题思路是使用或运算,一个for循环对2求i次幂(0次幂二进制1在第1位,1次幂则在第2位)然后和待求数进行或运算。因为2的i次幂除了第i+1位为1,其他都为0,做或运算时如果待求数该位也为1则不会改变待求数,这即是本题思路。注意!因为int是有符号数据类型,数据范围是-2,147,483,648到2,147,483,647。所以2的31次方在编译器中是2147483647而不是2147483648。因此需要特殊处理。代码如下:<div> public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; for(int i =0;i<32;i++){ int temp; temp = (int)Math.pow(2,i); if(i == 31) ...
2023-03-07

剑指offer(第二版)

0 阅读
0 评论
2023年03月07日
0 阅读
0 评论
2023-03-07

剪绳子2(中等)

剪绳子2(中等)
这道题和上一道的区别是:使用取模前的数字进行比较,输出结果要取模。因为有取模环节。其次这题数字很大,属于大数考察一开始做这题的时候想用int,发现必超内存,于是就想使用long,但是由于需要使用pow函数,该函数返回值是double,double强转long会丢失精度,会导致解题错误,于是最终妥协使用了BigInteger要注意BigInteger的使用,里面的取幂,乘积,比较等等都是需要该类下的指定函数的。下面是代码:<div> import java.math.BigInteger; class Solution { public int cuttingRope(int n) { BigInteger max = BigInteger.valueOf(0); //long max = 0; int s = (int)Math.sqrt(n); if(n == 1 || n ==2) return 1; if(n == 3) ret...
2023-03-07

剑指offer(第二版)

0 阅读
0 评论
2023年03月07日
0 阅读
0 评论