zoukankan      html  css  js  c++  java
  • Leetcode: Partition List

    思路:

    1. 空间复杂度为 o(n) 解法. 创建两个链表, 分别记录大于 x 和小于 x 的节点, 最后合并

    2. o(1) 的空间复杂度解法. 四个指针, 分别指向小于 x 部分链表的头, 尾, 指向大于 x 部分链表的头, 尾

    总结:

    1. 使用 dummyNode 减少判断

    代码:

    class Solution {
    public:
        ListNode *partition(ListNode *head, int x) {
            ListNode *first, *second, *third, *fourth;
    		if(head == NULL)
    			return head;
    
    		ListNode *cursor = head;
    		ListNode *dummyNode = new ListNode(0);
    		dummyNode->next = head;
    		first = second =  dummyNode;
    		while(cursor && cursor->val < x) { 
    			second = cursor;
    			cursor = cursor->next;
    		}
    		if(cursor && cursor->val >= x) {
    			third = cursor;
    			fourth = cursor;
    		}
    		while(cursor) {
    			if(cursor->val < x) {
    				second->next = cursor;
    				fourth->next = cursor->next;
    				cursor->next = third;
    				second = cursor;
    			}else{
    				fourth = cursor;
    			}
    			cursor = cursor->next;
    		}
    		return dummyNode->next;
        }
    };
    

      

    Update

    较为简洁的代码

    class Solution {
    public:
        ListNode *partition(ListNode *head, int x) {
            if(head == NULL)
                return head;
    
            ListNode *sm = new ListNode(0), *sm_tail = sm;
            ListNode *bg = new ListNode(0), *bg_tail = bg;
            ListNode *cur = head;
    
            while(cur) {
                if(cur->val < x) {
                    sm_tail->next = cur;
                    cur     = cur->next;
                    sm_tail = sm_tail->next;
                    sm_tail->next = NULL;
                }else{
                    bg_tail->next = cur;
                    bg_tail = bg_tail->next;
                    cur = cur->next;
                    bg_tail->next = NULL;
                }
            }
            sm_tail->next = bg->next;
            return sm->next;
        }
    };
  • 相关阅读:
    Java面试题 OOAD & UML+XML+SQL+JDBC & Hibernate
    Java面试题 corejava(二)
    Java面试题 corejava(一)
    Java 笔试题(一)
    大数据离线分析平台 用户数据Etl
    Spfa【p1186】 玛丽卡
    牛客nowcoder Noip提高组第四场
    分层图【p4568】 [JLOI2011]飞行路线
    10.06 国庆节第九场模拟赛
    10.04 国庆节第七场模拟赛
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3459997.html
Copyright © 2011-2022 走看看