- 數(shù)值的整數(shù)次方
遞歸一定不能忘了寫遞歸停止的判斷,另外還要注意expon是負(fù)值的情況(此處沒考慮)
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 位數(shù)
以n=2為例,寫成一個字符串s[i][j],先打印s[i],然后打印s[i][j],所以實際需要兩個循環(huán),先是s[0][j],然后是s[i][j],然后遞歸實現(xiàn)。
回頭一看,解題思路寫的邏輯真混亂啊,但是也不知道怎么改,還是寫具體實現(xiàn)……
//n的最大數(shù)打印
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,感覺當(dāng)前實現(xiàn)太繞,可以優(yōu)化
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) 時間內(nèi)刪除鏈表節(jié)點
看一下注釋
public static ListNode deleteNode(ListNode head, ListNode tobeDelete) {
if(head==null || head.next==null || tobeDelete == null) return null;
if(tobeDelete.next!=null) {
//刪除節(jié)點不是尾節(jié)點,則將刪除節(jié)點的下一個節(jié)點賦值給要刪除的節(jié)點,節(jié)點指向下一個的下一個節(jié)點
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 刪除鏈表中重復(fù)的結(jié)點
看著簡單,其實有陷阱
//刪除重復(fù)節(jié)點
public static ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null)
return pHead;
ListNode next = pHead.next;
//如果頭以及頭下一個節(jié)點相等,則需要返回不相等的節(jié)點作為頭;否則可以返回當(dāng)前頭作為頭,頭的下一個節(jié)點在刪除后的頭節(jié)點
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;
}
}