算法题

2019-02-17  本文已影响45人  黄靠谱

带答案的知乎回答啊,太良心了
https://www.zhihu.com/question/24964987

  1. 4G内存计算机,如何从1000亿个数中找到最大的1000个
    拆分+最小堆(比堆顶要小的数据,直接丢弃,比堆顶大的数据,则replace堆顶,再Sink)

  2. 单向链表中如何在O(1)内删除某一个节点

targetNode.value=targetNode.next.value
targetNode.next=targetNode.next.next
  1. 一次遍历找到单向链表中间节点
    设置2个游标一起走,第一个游标步长为2,第二个游标步长为1,当第一个游标遍历到链表的尽头时,就是中间节点

  2. 单向链表的排序(时间复杂度为 N*LogN)

public ListNode sortList(ListNode head) {
        return head == null ? null : mergeSort(head);
    }

    private ListNode mergeSort(ListNode head) {
        if (head.next == null) {
            return head;
        }
        ListNode p = head, q = head, pre = null;
        while (q != null && q.next != null) {
            pre = p;
            p = p.next;
            q = q.next.next;
        }
        //拆断了链表,把tail.next设置为null
        pre.next = null;
        ListNode l = mergeSort(head);
        ListNode r = mergeSort(p);
        return merge(l, r);
    }

    ListNode merge(ListNode l, ListNode r) {
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        while (l != null && r != null) {
            if (l.val <= r.val) {
                cur.next = l;
                cur = cur.next;
                l = l.next;
            } else {
                cur.next = r;
                cur = cur.next;
                r = r.next;
            }
        }
        if (l != null) {
            cur.next = l;
        }
        if (r != null) {
            cur.next = r;
        }
        return dummyHead.next;
    }
}
  1. 如何基于栈实现一个队列
    栈的特点:后进先出,队列的特点:FIFO,所以利用一个辅助的栈,可以实现FIFO,每次插入到栈中的时候,遍历从上面把所有的Entry Pop到辅助栈中,就可以实现FIFO了
上一篇 下一篇

猜你喜欢

热点阅读