LeetCode刷题打卡群 Week5

面试题 08.06. 汉诺塔问题

class Solution {
    public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
        if(A==null) return;
        recurse(A, B, C, A.size());
    }

    public void recurse(List<Integer> src, List<Integer> tmp, List<Integer> tar, int num) {
        if(num<=0) return;
        recurse(src, tar, tmp, num-1);      //将src上面n-1移到tmp
        tar.add(src.remove(src.size()-1));  //将src的第n移到tar
        recurse(tmp, src, tar, num-1);      //将tmp的n-1移到tar
    }
}

148. 排序链表

class Solution {
    public ListNode sortList(ListNode head) {
        int size = getSize(head);
        int nLen = 1;   //层数 1 2 4 8...
        ListNode dumbHead = new ListNode(Integer.MIN_VALUE, head);
        ListNode prev, currHead;
        ListNode l1, l2;    //合并队列的起点
        int i;
        while (nLen < size) {
            prev = dumbHead; currHead = dumbHead.next;
            while (currHead != null) {
                l1 = currHead; l2 = currHead;
                //获取l2
                i = 1;
                while (i <= nLen && l2.next != null) {
                    l2 = l2.next;
                    i++;
                }
                if (i <= nLen) break;   //l2为空 直接返回
                //获取l2长度及下一个currHead
                currHead = l2;
                i = 1;
                while (i <= nLen && currHead != null) {
                    currHead = currHead.next;
                    i++;
                }
                prev = mergeListNode(prev, currHead, l1, nLen, l2, i-1);
            }
            nLen *= 2;
        }
        return dumbHead.next;
    }

    private int getSize(ListNode node) {
        int size = 0;
        while (node != null) {
            size++;
            node = node.next;
        }
        return size;
    }

    private ListNode mergeListNode(ListNode prev, ListNode nextHead, ListNode l1, int e1, ListNode l2, int e2) {
        while (e1 > 0 && e2 > 0) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
                e1--;
            } else {
                prev.next = l2;
                l2 = l2.next;
                e2--;
            }
            prev = prev.next;
        }
        prev.next = l1;
        int r = e1;
        if (e1 <= 0) {
            prev.next = l2;
            r = e2;
        }
        while (r-- > 0) {
            prev = prev.next;
        }
        prev.next = nextHead;
        return prev;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值