- 数值的整数次方
递归一定不能忘了写递归停止的判断,另外还要注意expon是负值的情况(此处没考虑)
public static double Power(double base, int expon) {
// 注意递归停止的判断
if (expon == 0)
return 1;
if (expon == 1)
return base;
double pow = Power(base * base, expon / 2);
if (expon % 2 != 0) {
pow = pow * base;
}
return pow;
}
- 打印从 1 到最大的 n 位数
以n=2为例,写成一个字符串s[i][j],先打印s[i],然后打印s[i][j],所以实际需要两个循环,先是s[0][j],然后是s[i][j],然后递归实现。
回头一看,解题思路写的逻辑真混乱啊,但是也不知道怎么改,还是写具体实现……
//n的最大数打印
public static void printMax(int n) {
if(n<1) return;
StringBuffer s= new StringBuffer(n);
for(int i=0;i<n;i++) {
s.append('0');
}
for(int i=0;i<n;i++) {
s.setCharAt(0, (char)(i+'0'));
printMaxcore(n,s,0);
}
}
public static void printMaxcore(int n,StringBuffer s,int index) {
if(n==index+1){
prints(s);
return;
}
for(int i=0;i<10;i++) {
s.setCharAt(index+1, (char)(i+'0'));
printMaxcore(n,s,index+1);
}
}
public static void prints(StringBuffer s) {
//从s[i][j]的左到右依次检查是否为0,感觉当前实现太绕,可以优化
boolean isBeginning0 = false;
for(int i=0;i<s.length();i++) {
if (s.charAt(i) != '0') {
isBeginning0 = true;
}
if (isBeginning0) {
System.out.print(s.charAt(i));
}
}
System.out.println();
}
18.1 在 O(1) 时间内删除链表节点
看一下注释
public static ListNode deleteNode(ListNode head, ListNode tobeDelete) {
if(head==null || head.next==null || tobeDelete == null) return null;
if(tobeDelete.next!=null) {
//删除节点不是尾节点,则将删除节点的下一个节点赋值给要删除的节点,节点指向下一个的下一个节点
ListNode next=tobeDelete.next;
tobeDelete.val=next.val;
tobeDelete.next= next.next;
} else {
ListNode cur=head;
while(cur.next != tobeDelete){
cur=cur.next;
}
cur.next=null;
}
return head;
}
18.2 删除链表中重复的结点
看着简单,其实有陷阱
//删除重复节点
public static ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null)
return pHead;
ListNode next = pHead.next;
//如果头以及头下一个节点相等,则需要返回不相等的节点作为头;否则可以返回当前头作为头,头的下一个节点在删除后的头节点
if (pHead.val == next.val) {
while (next != null && pHead.val == next.val)
next = next.next;
return deleteDuplication(next);
} else {
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
网友评论