zoukankan      html  css  js  c++  java
  • Leetcode 148 with Quicksort

    class Solution {
        void quicksort(ListNode* head, ListNode* tail) {
            if (head == nullptr || head == tail) return;
            ListNode* slow, *fast;
            slow = head;
            fast = head->next;
            while (fast != tail) {
                if (fast->val < head->val) {
                    slow = slow->next;
                    swap(slow->val, fast->val);
                }
                fast = fast->next;
            }
            swap(slow->val, head->val);
            quicksort(head, slow);
            quicksort(slow->next, tail);
        }
    public:
        ListNode* sortList(ListNode* head) {
            if (head == nullptr) {
                return head;
            }
            quicksort(head, nullptr);
            return head;
        }
    };

    两个指针,fast 指向大元素链表尾部,slow 指向小元素链表尾部,slow->next 是大元素链表头部。

    遇到需要放在小元素链表的元素,我们就 slow = slow -> next,占用大元素链表头部的空间放置小元素。而原来的大元素链表头部的元素用值交换的放置放到链表末尾。

    昨天面试遇到了这道题,只能说我还是太嫩了,我还想着维护整个链表的头和尾,然后修改链表指向来完成快排……

  • 相关阅读:
    UVA11367 Full Tank?
    不均衡样本集问题
    NLP interview
    Linux 指令
    Python 趣题
    Grid Illumination
    动态规划-Minimum Cost to Merge Stones
    Contest 141
    Python join()方法
    Single Number
  • 原文地址:https://www.cnblogs.com/KakagouLT/p/13678056.html
Copyright © 2011-2022 走看看