21. 合併兩個有序鏈表
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(-1);
ListNode curr = dummyHead;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
curr.next = l1;
curr = curr.next;
l1 = l1.next;
}else{
curr.next = l2;
curr = curr.next;
l2 = l2.next;
}
}
if(l1==null){
curr.next = l2;
}
if(l2==null){
curr.next = l1;
}
return dummyHead.next;
}
}
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
if(l1.val<=l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
}
面試題14- II. 剪繩子 II
class Solution {
public int cuttingRope(int n) {
if(n == 2)
return 1;
if(n == 3)
return 2;
long res = 1;
while(n > 4){
res *= 3;
res = res % 1000000007;
n -= 3;
}
return (int)(res * n % 1000000007);
}
}
你知道的越多,你不知道的越多。